次の方法でスレッドのポートをリッスンします。 WaitOne
メソッドで待機している間、私はスレッドを停止します(私はIsCancellationRequestedを真にしています)。listener
オブジェクトを閉じることができません。それから私は同じポートを聞きたいときにエラーが発生します。スレッドを停止した後、変数でリスン操作をキャンセルできますか?
リスナーオブジェクトを変数にバインドできますか?その変数がfalseの場合、自動シャットダウンを行います。
スレッドが別のスレッドで停止していることを確認したくない場合は、listener
を閉じてください。
public void StartListening(Connection connection)
{
// There are codes here..
try
{
listener.Bind(localEndPoint);
listener.Listen(2);
while (connection.CancellationTokenSource.IsCancellationRequested == false)
{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
allDone.WaitOne(); // While I'm waiting here, I'm making the 'IsCancellationRequested' variable true.
}
listener.Close();
}
catch (Exception e)
{
// There are codes here..
}
// There are codes here..
}
注:Connection
クラスは、私はそれがSystem.Threading.CancellationTokenSource CancellationTokenSource
プロパティが含まれて作成したクラスです。
「listener.Close();」をfinallyブロックに入れることができます。しかしそれはテープソリューションです。スレッドを終了するのは恐ろしい解決策です。 –