【发布时间】:2012-03-27 12:36:47
【问题描述】:
我有一个文件传输应用程序(服务器-客户端)...在发送文件时,我想启用取消。
客户端取消后台工作程序的 SendFile 方法,然后向服务器发送命令以取消其接收线程。
当服务器收到此命令时,它会调用 Stop 方法 但它停留在该行 network.Read(data, 0, data.Length);
我怎样才能中止这个线程并转到 finally 而不会卡在 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的重载效果最好。否则,正如@Daniel Mošmondor 所说,Close或Disposenetwork对象。
标签: c# cancellation thread-abort