#17868: Isolating background tasks

Work Items: 17868

--HG--
branch : 1.x
This commit is contained in:
Sebastien Ros
2011-09-14 17:13:33 -07:00
parent 877f1b3507
commit 7eb2967141
2 changed files with 23 additions and 25 deletions

View File

@@ -1,4 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using JetBrains.Annotations;
using Orchard.Data;
using Orchard.Events;
using Orchard.Logging;
namespace Orchard.Tasks {
@@ -9,9 +15,9 @@ namespace Orchard.Tasks {
[UsedImplicitly]
public class BackgroundService : IBackgroundService {
private readonly IBackgroundTask _tasks;
private readonly IEnumerable<IEventHandler> _tasks;
public BackgroundService(IBackgroundTask tasks) {
public BackgroundService(IEnumerable<IEventHandler> tasks) {
_tasks = tasks;
Logger = NullLogger.Instance;
}
@@ -19,7 +25,17 @@ namespace Orchard.Tasks {
public ILogger Logger { get; set; }
public void Sweep() {
_tasks.Sweep();
foreach(var task in _tasks.OfType<IBackgroundTask>()) {
using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew)) {
try {
task.Sweep();
scope.Complete();
}
catch (Exception e) {
Logger.Error(e, "Error while processing background task");
}
}
}
}
}
}

View File

@@ -5,7 +5,7 @@ using Orchard.Environment;
using Orchard.Logging;
namespace Orchard.Tasks {
public class SweepGenerator : IOrchardShellEvents, IDisposable {
public class SweepGenerator : IOrchardShellEvents {
private readonly IWorkContextAccessor _workContextAccessor;
private readonly Timer _timer;
@@ -55,29 +55,11 @@ namespace Orchard.Tasks {
}
public void DoWork() {
// makes an inner container, similar to the per-request container
using (var scope = _workContextAccessor.CreateWorkContextScope()) {
var transactionManager = scope.Resolve<ITransactionManager>();
try {
// resolve the manager and invoke it
var manager = scope.Resolve<IBackgroundService>();
manager.Sweep();
}
catch {
// any database changes in this using scope are invalidated
transactionManager.Cancel();
// pass exception along to actual handler
throw;
}
// resolve the manager and invoke it
var manager = scope.Resolve<IBackgroundService>();
manager.Sweep();
}
}
public void Dispose()
{
_timer.Elapsed -= Elapsed;
_timer.Dispose();
}
}
}