C# 任务:异常和取消
我需要做一个长时间的任务。我通过在UI上有一个加载框的情况下执行一个任务来实现这一点。当抛出异常时,我想停止任务并向用户显示一个msgbox。如果一切顺利,我会停止装货箱 下面的代码按预期工作,但我想知道我在这里做的是否正确,因为这是我第一次做这样的事情C# 任务:异常和取消,c#,task,.net-4.5,C#,Task,.net 4.5,我需要做一个长时间的任务。我通过在UI上有一个加载框的情况下执行一个任务来实现这一点。当抛出异常时,我想停止任务并向用户显示一个msgbox。如果一切顺利,我会停止装货箱 下面的代码按预期工作,但我想知道我在这里做的是否正确,因为这是我第一次做这样的事情 private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); protected void
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
停止此加载框,并显示一条消息,说明编程是否成功完成。
两者都有用户界面线程作为订阅者。我在代码审查中也提出了这个问题,因为这里不是合适的地方。 对于那些偶然发现这个问题并想知道答案的人: