2017-04-17 87 views
2

我正在運行一項任務。關閉窗口時,我正在嘗試使用取消標記來源取消任務。每當窗口關閉時都不會發生錯誤。只是有時。請看一看錯誤我得到任務被取消

enter image description here

private CancellationTokenSource dotIndicatorTokenSource; 
    private void BlinkDotIndicator() 
    { 

     var halfPeriod = 200; 

     dotIndicatorTokenSource = new CancellationTokenSource(); 
     Task.Factory.StartNew(() => 
     { 
      while (true) 
      { 
       Dispatcher.Invoke(() => 
       { 
        connectionIndicatorDotImg.Visibility = Visibility.Hidden; 
       }); 
       Thread.Sleep(halfPeriod); 

       Dispatcher.Invoke(() => 
       { 
        connectionIndicatorDotImg.Visibility = Visibility.Visible; 
       }); 

       Thread.Sleep(halfPeriod); 

       if (dotIndicatorTokenSource.IsCancellationRequested) 
       { 
        break; 
       } 

      } 
     }, dotIndicatorTokenSource.Token); 

    } 


    private void Window_Closing(object sender, CancelEventArgs e) 
    { 
     if (dotIndicatorTokenSource != null) 
      dotIndicatorTokenSource.Cancel(); 
    } 

回答

2

當您運行的代碼,檢查是否取消之前和之後掛起,並在兩者之間。這樣,如果在操作過程中被取消,則不會執行下一個分派器功能。

 while (true) 
     { 
      if (dotIndicatorTokenSource.IsCancellationRequested) 
      { 
       break; 
      } 

      Dispatcher.Invoke(() => 
      { 
       connectionIndicatorDotImg.Visibility = Visibility.Hidden; 
      }); 
      Thread.Sleep(halfPeriod); 

      if (dotIndicatorTokenSource.IsCancellationRequested) 
      { 
       break; 
      } 

      Dispatcher.Invoke(() => 
      { 
       connectionIndicatorDotImg.Visibility = Visibility.Visible; 
      }); 

      Thread.Sleep(halfPeriod); 

      if (dotIndicatorTokenSource.IsCancellationRequested) 
      { 
       break; 
      } 

     } 
+0

哦,我明白了。遵循這個邏輯,是否真的有必要最終檢查取消? –

+0

Eh。沒有?不是真的。但它是在睡眠之後。所以這並不重要。爲什麼不安全。這是4行代碼。而且你甚至不會進入下一個循環。 –