サーバーから送信されたバイトデータを読み取ろうとするクラスを作成しました。アプリが終了したら、ループも終了したいのですが、NetworkStream.Read()
データが利用できない場合は待機しているように見えます。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Threading.Tasks;
namespace Stream
{
class Program
{
private static TcpClient client = new TcpClient("127.0.0.1", 80);
private static NetworkStream stream = client.GetStream();
static void Main(string[] args)
{
var p = new Program();
p.Run();
}
void Run()
{
ThreadPool.QueueUserWorkItem(x =>
{
while (true)
{
stream.Read(new byte[64], 0, 64);
}
});
client.Close();
// insert Console.ReadLine(); if you want to see an exception occur.
}
}
}
このコードを使用すると、
System.IO.IOException
「トランスポート接続からデータを読み取れません:既存の接続がリモートホストによって強制的に閉じられました」と表示されます。ObjectDisposedException
「廃棄されたオブジェクトにアクセスできません」と言ったり、System.IO.IOException
「WSACancelBlockingCallの呼び出しによってブロッキング操作が中断されました」と表示されます。
では、どうすればこのメソッドを安全に終了できますか?