优雅地退出一个线程

时间:2014-02-05 10:43:32

标签: c# .net multithreading

我正在用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上发布的其他方法,但是我无法理解它们(我对多线程很新)。优选地,我可以检查我的父对象bool上的reference开关。 IE:

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

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

任何人都可以向我指出一个好资源或者给我一个关于我应该搜索什么搜索条件的提示,或者如果你真的有心情,可能会做一个如何处理这个问题的模型吗? / p>

1 个答案:

答案 0 :(得分: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