public void RunAsync(int OperationId, string Code, ErpType Erp, bool Forced, Action <TaskStatus> After) { var ts = new CancellationTokenSource(); CancellationToken ct = ts.Token; Task newTask = Task.Run(async() => { void setScope() { IOperationScope scope = container.GetInstance <IOperationScope>(); scope.Provide(OperationId, ct); } try { using (AsyncScopedLifestyle.BeginScope(container)) { setScope(); ITaskFinder finder = container.GetInstance <ITaskFinder>(); (bool IsAsync, object Task)item = finder.Get(Code, Erp); TaskStatus status; if (item.IsAsync) { status = await(item.Task as ITaskAsync).Execute(); } else { status = (item.Task as ITask).Execute(); } After(status); } } catch (Exception e) { /* Use a different scope to ignore all the data inserted before */ using (AsyncScopedLifestyle.BeginScope(container)) { setScope(); ITaskLogger logger = container.GetInstance <ITaskLogger>(); await logger.Insert(e, $"Task {Code}"); bool cancelled = IsCancelledException(e); After(cancelled ? TaskStatus.Cancelled : TaskStatus.Error); } } }, ct); JobTrack track = new JobTrack() { JobCode = Code, Task = newTask, TokenSource = ts, OperationId = OperationId }; tracker.Add(track); }