如何在我用C#创建的非托管DLL中停止一个线程

时间:2011-09-28 14:14:17

标签: c# dll thread-safety

我有一个C#DLL,它启动一个线程来轮询USB设备。我的问题是workerObject函数中的workerThreadStopListenUSBnull

public class USBDevice
{
   private Worker workerObject;
   private Thread workerThread;

   public void StartListenUSB(int hwnd, uint wm_USER_KEYBOARD)
   {
      workerObject = new Worker();
      workerThread = new Thread(workerObject.DoWork);
      workerThread.Start();
   }

   public void StopListenUSB()
   {
      workerObject.RequestStop();
      workerThread.Join();
   }
}

public class Worker
{
   private volatile bool _shouldStop;

   public void RequestStop() { _shouldStop = true; }

   public void DoWork()
   {
      while (!_shouldStop)
      {...}
   }
}

0 个答案:

没有答案