我有一个文件传输应用程序(服务器-客户端)......在发送文件时,我想启用取消。
客户端取消它由后台工作者工作的 SendFile 方法,然后它向服务器发送命令以取消其接收线程。
当服务器收到此命令时,它调用Stop 方法,但它停留在该行network.Read(data, 0, data.Length);
我怎样才能中止这个线程并最终进入而不会卡在 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);
}
}
}