私はむしろTcpClient
そのスピンを使ってクラスを持ってThread
いwhile (!streamReader.EndOfStream) {}
ますNetworkStream
。TCP 接続が開いていて、読み取るデータがない限り、EndOfStream
実行がブロックされるため、スレッド外からの読み取りを中止するにはどうすればよいでしょうか。
がブロックされているため、呼び出されEndOfStream
たプライベート フィールドを設定しても (少なくとも私のテストでは) 単独ではあまり効果がありません。そのため、私が行ったことは次のとおりです。stop
true
// Inside the reading thread:
try
{
StreamReader streamReader = new StreamReader(this.stream);
while (!streamReader.EndOfStream)
{
// Read from the stream
}
}
catch (IOException)
{
// If it isn't us causing the IOException, rethrow
if (!this.stop)
throw;
}
// Outside the thread:
public void Dispose()
{
// Stop. Hammer Time!
this.stop = true;
// Dispose the stream so the StreamReader is aborted by an IOException.
this.stream.Dispose();
}
これは a からの読み取りを中止するための推奨される方法ですか、NetworkStream
それとも安全に (ただし強制的に) すべてを破棄するために使用できる他の手法はありますか?