winform中的线程-Compact.NET Framework 3.5

本文关键字:Framework NET -Compact 线程 winform | 更新日期: 2023-09-27 18:30:07

我在一个函数中有一个线程,它启动实时监控,基本上是打开串口并连续从串口读取数据。但是,如果我需要终止这个线程,我应该怎么做?因为如果我不终止打开特定串行端口并读取数据的运行线程。当我关闭它并再次调用函数时。无法打开同一串行端口。我怀疑串行端口没有正确关闭,并且仍在单独的线程中运行。所以我想我必须终止那个线程,以便下次再次打开同一个串行端口。有人知道如何做到这一点吗?

我看到一些论坛说Thread.Artrt()使用起来很危险。它只能在万不得已的情况下使用。

谢谢你的帮助。

Charles

winform中的线程-Compact.NET Framework 3.5

通常,您可以设计在后台线程中运行的方法来侦听取消请求。这可以像布尔值一样简单:

//this simply provides a synchronized reference wrapper for the Boolean,
//and prevents trying to "un-cancel"
public class ThreadStatus
{
   private bool cancelled;
   private object syncObj = new Object();
   public void Cancel() {lock(syncObj){cancelled = true;}}
   public bool IsCancelPending{get{lock(syncObj){return cancelled;}}}
}
public void RunListener(object status)
{
   var threadStatus = (ThreadStatus)status;
   var listener = new SerialPort("COM1");
   listener.Open();
   //this will loop until we cancel it, the port closes, 
   //or DoSomethingWithData indicates we should get out
   while(!status.IsCancelPending 
         && listener.IsOpen 
         && DoSomethingWithData(listener.ReadExisting())
      Thread.Yield(); //avoid burning the CPU when there isn't anything for this thread
   listener.Dispose();
}
...
Thread backgroundThread = new Thread(RunListener);
ThreadStatus status = new ThreadStatus();
backgroundThread.Start(status);
...
//when you need to get out...
//signal the thread to stop looping
status.Cancel();
//and block this thread until the background thread ends normally.
backgroundThread.Join()

首先认为你有线程,要关闭所有线程,你应该在启动它们之前将所有线程设置为后台线程,然后当应用程序退出时,它们将自动关闭。

然后尝试这种方式:

Thread somethread = new Thread(...);
someThread.IsBackground = true;
someThread.Start(...); 

请参阅http://msdn.microsoft.com/en-us/library/aa457093.aspx

使用一个布尔标志,最初设置为false,当您希望线程退出时,将其设置为true。显然,您的主线程循环需要监视该标志。当它看到它变为true时,请关闭端口并退出主线程循环。

你的主循环可能看起来像这样:

OpenPort();
while (!_Quit)
{
    ... check if some data arrived
    if (!_Quit)
    {
        ... process data
    }
}
ClosePort();

根据等待新数据的方式,您可能希望使用事件(ManualResetEventAutoResetEvent),以便在希望线程退出时唤醒线程。