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