2013-06-04 57 views
0

我需要執行長時間運行的任務。我通過在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

我也在代碼審查也提問這個問題,因爲這裏並不是完全正確的地方。 對於那些絆倒這個問題,並想知道答案的人:you can find it here