我需要做一个长期运行的任务。我通过在 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 线程作为订阅者。