私はファイル転送アプリケーション(サーバークライアント)を持っています...ファイルを送信中に、私はキャンセルを有効にしたいと思います。
クライアントBackgroundworkerが動作するSendFileメソッドをキャンセルし、サーバーに受信スレッドをキャンセルするコマンドを送信します。
サーバがこのコマンドを受信したときに、メソッドを停止します。メソッドを停止しますが、その行にスタックします。network.Read(data、0、data.Length);Thread.Abort()がNetworkStream.Readにスタックしましたか?
このスレッドを中止してに移動するにはどうすればいいですか? network.Read(..)にくっついていませんか?ありがとうございます。
Thread thTransferFile = null;
void Start()
{
thTransferFile = new Thread(unused => ft.Receive(destPath, Convert.ToInt64(fileSize);
thTransferFile.Start();
}
void Stop()
{
thTransferFile.Abort();
}
public void Receive(string destPath, long fileSize)
{
using (fs = new FileStream(destPath, FileMode.Create, FileAccess.Write))
{
try
{
int count = 0;
long sum = 0;
data = new byte[packetSize];
while (sum < fileSize)
{
count = network.Read(data, 0, data.Length); //thread stucks in this line when i abort it
fs.Write(data, 0, count);
sum += count;
}
}
finally
{
network.Write(new byte[1], 0, 1); //tell client that the file transfer ends
network.Flush();
fs.Dispose();
if (Thread.CurrentThread.ThreadState == ThreadState.AbortRequested)
{
File.Delete(destPath);
}
}
}
'Thread.Abort'は*ほとんど常に*間違ったことです。 –
@Damien_The_Unbelieverだからそれが間違っているなら何が正しいことですか? –
それはあなたが感じている勇気にかかっています。もしあなたが.NET 4.5へのジャンプをする準備ができていれば、 'CancellationToken'をとる' ReadAsync'のオーバーロードが一番うまくいくでしょう。さもなければ、@DanielMošmondorが言うように、 'network'オブジェクトを' Close'または 'Dispose'します。 –