我正在用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
}
}我曾经尝试过其他方法在Stackoverflow上发布,但是我无法理解它们(我对多线程很陌生)。最好只是在我的父对象reference上有一个reference开关,我可以检查它。IE:
public class Reference
{
public static bool gracefulStopRequested = false;
}
public void PollUSBDevice
{
while (ec == ErrorCode.None && !reference.gracefulStopRequested)
{
....
}
}谁能告诉我一个好的资源,或者给我一个提示,我应该搜索什么搜索词,或者如果你有一个真正的给予情绪,可能做一个模型,你将如何处理这个问题?
发布于 2014-02-05 10:53:20
我会去做这样的事情:
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
https://stackoverflow.com/questions/21574979
复制相似问题