2

ライブモニタリングを開始する関数にスレッドがあります。基本的に、シリアルポートを開き、シリアルポートからデータを継続的に読み取ります。ただし、このスレッドを終了する必要がある場合、どのようにすればよいですか? 特定のシリアルポートを開いてデータを読み取っている実行中のスレッドを終了しないと。それを閉じて、関数を再度呼び出すと。同じシリアル ポートを開くことはできません。シリアル ポートが適切に閉じられておらず、別のスレッドで実行されていると思われます。そのため、次回同じシリアルポートを開くには、そのスレッドを終了する必要があると思います。これを達成する方法を知っている人はいますか?

Thread.Abort() を使用するのは危険であるというフォーラムを見たことがあります。最後の手段でのみ使用してください。

助けてくれてありがとう。

チャールズ

4

3 に答える 3

3

一般に、バックグラウンド スレッドで実行され、キャンセル要求をリッスンするメソッドを設計します。これは、ブール値と同じくらい簡単です。

//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()
于 2012-04-04T22:37:18.883 に答える
2

まず、スレッドが含まれていると考えてください。すべてのスレッドを閉じるには、開始する前にすべてのスレッドをバックグラウンド スレッドに設定する必要があります。アプリケーションが終了すると、それらは自動的に閉じられます。

そして、この方法を試してください:

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

http://msdn.microsoft.com/en-us/library/aa457093.aspxを参照してください

于 2012-04-04T22:23:02.903 に答える
1

最初に false に設定したブール値フラグを使用し、スレッドを終了させたい場合は true に設定します。どうやらメインスレッドループはそのフラグを監視する必要があります。true に変化したことが確認できたら、ポーリングを終了し、ポートを閉じてメイン スレッド ループを終了します。

メインループは次のようになります。

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

新しいデータを待つ方法によっては、終了したいときにスレッドを起動するために、イベント (ManualResetEventまたは) を利用したい場合があります。AutoResetEvent

于 2012-04-04T22:28:12.567 に答える