我需要做一个长期运行的任务。我已经通过执行任务来完成此操作,而UI上有一个加载框。抛出异常时,我想停止任务并向用户显示一个msgbox。如果一切顺利,我会停止装箱。
下面的代码按预期工作,但我想知道我在这里是否正确,因为这是我第一次这样做。
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
protected void ProgramImage()
{
this.OnProgrammingStarted(new EventArgs());
var task =
Task.Factory.StartNew(this.ProgramImageAsync)
.ContinueWith(
this.TaskExceptionHandler,
cancellationTokenSource.Token,
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext()) //Catch exceptions here
.ContinueWith(
o => this.ProgramImageAsyncDone(),
cancellationTokenSource.Token,
TaskContinuationOptions.NotOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext()); //Run this when no exception occurred
}
private void ProgramImageAsync()
{
Thread.Sleep(5000); // Actual programming is done here
throw new Exception("test");
}
private void TaskExceptionHandler(Task task)
{
var exception = task.Exception;
if (exception != null && exception.InnerExceptions.Count > 0)
{
this.OnProgrammingExecuted(
new ProgrammingExecutedEventArgs { Success = false, Error = exception.InnerExceptions[0] });
this.Explanation = "An error occurrred during the programming.";
}
// Stop execution of further taks
this.cancellationTokenSource.Cancel();
}
private void ProgramImageAsyncDone()
{
this.OnProgrammingExecuted(new ProgrammingExecutedEventArgs { Success = true });
this.Explanation = ResourceGeneral.PressNextBtn_Explanation;
this.IsStepComplete = true;
}
事件OnProgrammingStarted
显示UI线程上的加载框。
事件OnProgrammingExecuted
会停止此加载框,并显示编程是否已成功完成的消息。
两者都将UI线程作为订阅者。
答案 0 :(得分:0)
我也在 Code Review 上提出了这个问题,因为这里并不是正确的地方。 对于那些偶然发现这个问题并希望知道答案的人:you can find it here