簡體   English   中英

winform 中的線程 - Compact .NET Framework 3.5

[英]Threading in winform - Compact .NET Framework 3.5

我在 function 中有一個線程啟動實時監控,它基本上打開串口並不斷從串口讀取數據。 但是,如果我需要終止這個線程,我應該怎么做呢? 因為如果我不終止打開特定串口和讀取數據的運行線程。 當我關閉它並再次撥打 function 時。 同一個串口打不開。 我懷疑串行端口沒有正確關閉並且仍在單獨的線程中運行。 所以我想我必須終止那個線程,以便下次再次打開同一個串行端口。 有誰知道如何實現這一目標?

我看到一些論壇說 Thread.Abort() 使用起來很危險。 它應該只在最后的手段中使用。

感謝您的幫助。

查爾斯

通常,您設計在后台線程中運行的方法來偵聽取消請求。 這可以像 boolean 值一樣簡單:

//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 的 boolean 標志,當您希望線程退出時,將其設置為 true。 顯然,您的主線程循環需要監視該標志。 當它看到它變為 true 時,就停止輪詢,關閉端口並退出主線程循環。

您的主循環可能如下所示:

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

根據您等待新數據的方式,您可能希望使用事件( ManualResetEventAutoResetEvent )以便在您希望它退出時喚醒您的線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM