2017-07-01 196 views
0

我情況下,我必須使用Task.Run在我ForEach循環如何殺死或中止Task.Run或Task.Factory.StartNew()在C#

要求: 我將被迫手動殺死線程 我有按鈕,我可以在For循環中啓動和停止此ThreadTask.Run

問題 我的問題是,當我開始Task.Run方法及其運行,但是當我試圖停止使用CancellationTokenSourcerunningTaskThread.Abort();它不會殺死。它剛剛停止時,我開始新的Task.Run在那個時候它運行與舊的線程,所以它成爲多個線程的每個啓動過程。

代碼:

下面是我開始線程代碼

var messages = rootObject.MultiQData.Messages.Where(m => m.TimeStamp > DateTime.Now).OrderBy(x => x.TimeStamp).ToList(); 
           //Simulate MultiQ file in BackGroud 
           if (messages.Count > 0) 
           { 
            cancellationTokenSource = new CancellationTokenSource(); 
            cancellationToken = cancellationTokenSource.Token; 
            Task.Factory.StartNew(
             () => 
             { 
              runningTaskThread = Thread.CurrentThread; 
              messages.ForEach(
               m => SetUpTimer(m, rootObject.MultiQData.Connection.FleetNo)); 
             }, cancellationToken); 
           } 

對於停止Task.Run

if (cancellationTokenSource != null) 
      { 
       if (cancellationToken.IsCancellationRequested) 
        return; 
       else 
        cancellationTokenSource.Cancel(); 
      } 

我還用ThreadThread.Abort但它不工作

請幫助解決這個問題

回答

0

我使用timer.Stop(),timer.Dispose()得到了解決。在創建線程我打電話SetUpTimer和這個SetupTimer我創建了多個計時器。

所以在停止線的電話,我有處置定時器,它的工作對我來說

更多信息參見下面的代碼

private void SetUpTimer(Message message, string fleetNo) 
     { 
      var ts = new MessageTimer(); 

      var interval = (message.TimeStamp - DateTime.Now).TotalMilliseconds; 
      interval = interval <= 0 ? 100 : interval; 

      ts.MessageWrapper = new MessageWrapper(message, fleetNo); 
      ts.Interval = interval; 
      ts.Elapsed += ts_Elapsed; 
      ts.Start(); 

      //Add timer in to the lost for disposing timer at time of stop Simulation 
      lsTimers.Add(ts); 
     } 
private void StopTask() 
    { 
     try 
     { 
      // Attempt to cancel the task politely 
      if (cancellationTokenSource != null) 
      { 
       if (cancellationToken.IsCancellationRequested) 
        return; 
       else 
        cancellationTokenSource.Cancel(); 
      } 

      //Stop All Timer 
      foreach (var timer in lsTimers) 
      { 
       timer.Stop(); 
       timer.Dispose(); 
      } 
     } 
     catch (Exception ex) 
     { 
      errorLogger.Error("Error while Stop simulation :", ex); 
     } 

    }