2014-02-05 148 views
0

我正在C#中開發多線程應用程序,現在我已經意識到我的線程有時會在我通過.Abort(); .Join();方法停止它們時拋出錯誤。優雅地退出線程

我的啓動和停止線程當前的代碼如下:

public void StartLogging() 
    { 
     if (poller != null && poller.IsAlive) 
     { 
      poller.Abort(); 
      poller.Join(); 
     } 
     poller = new Thread(new ThreadStart(PollUSBDevice)); 
     poller.IsBackground = true; 
     poller.Name = reference.VendorId.ToString() + ":" + reference.ProductId.ToString(); 
     poller.Start(); 
     IsLogging = true; 
    } 

public void StopLogging() 
    { 
     if (poller != null && poller.IsAlive) 
     { 
      poller.Abort(); 
      poller.Join(); 
      IsLogging = false; 
     } 
    } 

private void PollUSBDevice() 
    { 
     ...Removed code - executes within milliseconds and I am not worried about stopping here. 

     ErrorCode ec = ErrorCode.None; 

      ### THIS LOOPS FOR EVER OR UNTIL I CALL .Abort() ### 
      while (ec == ErrorCode.None && MyUsbDevice.IsOpen) 
      { 
       if (poller.ThreadState == System.Threading.ThreadState.AbortRequested) 
       { 
        reader.Abort(); 
        reader.Dispose(); 
        break; 
       } 
       else 
       { 
        byte[] readBuffer = new byte[8]; 
        int bytesRead; 
        ec = reader.Read(readBuffer, 100, out bytesRead); 

        Application.Current.Dispatcher.BeginInvoke(
         new OneArgDelegate(HandleData), 
         new object[] { readBuffer }); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      Do stuff.... 
     } 
     finally 
     { 
      Close devices that are running in above while statement 
     } 
    } 

我曾嘗試其他方法在這裏發佈#2,但我不能讓我的頭周圍(我新望到多線程)。最好是,我可以檢查的父母對象reference上只有一個bool開關。 IE:

public class Reference 
{ 
    public static bool gracefulStopRequested = false; 
} 

public void PollUSBDevice 
{ 
    while (ec == ErrorCode.None && !reference.gracefulStopRequested) 
    { 
     .... 
    } 
} 

任何人都可以指向我一個很好的資源,或給我一個提示,我應該尋找怎樣的搜索字詞的,或者如果你是一個真正讓情緒,可能做的怎麼樣,你一個樣機會處理這個問題?

回答

1

我會去是這樣的:

class Program 
{ 
    static void Main(string[] args) 
    { 
     Thread poller = new Thread(new ThreadStart(PollUSBDevice)); 
     poller.Start(); 

     Console.ReadLine(); 

     StopPoller(); 

     Console.WriteLine("Stopped"); 
     Console.ReadLine(); 
    } 

    public static void StopPoller() 
    { 
     _PollerStopRequested = true; 
    } 

    private static bool _PollerStopRequested = false; 
    private static void PollUSBDevice() 
    { 
     while (true && !_PollerStopRequested) 
     { 
      Console.WriteLine("running"); 
      Thread.Sleep(500); 
     } 
    } 
} 

然而,這僅僅是模擬在C#BackgroundWorker功能構建,所以你也可以看看:http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.110).aspx