Thread.Artrt()在NetworkStream.Read处卡住

本文关键字:Read NetworkStream Artrt Thread | 更新日期: 2023-09-27 18:27:16

我有一个文件传输应用程序(服务器客户端)。。。发送文件时,我想启用取消功能。
客户端取消它由后台工作人员工作的SendFile方法,然后它向服务器发送一个命令以取消其接收线程
当服务器收到此命令时,它调用Stop方法,但它卡在网络中。Read(data,0,data.Length)

如何在不阻塞网络的情况下中止此线程并最终转到。阅读(..)??
提前谢谢。

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.Artrt()在NetworkStream.Read处卡住

Close()不是中止线程,而是network。它会像您预期的那样抛出异常。

杀死线程是一个很大的禁忌,因为有些资源可以不清理。。。

NetworkStream.Read在接收数据之前被阻止。使用NetworkStream的ReadTimeout read the community comment设置读取操作的超时。此外,您可能需要重新考虑使用Abort()来终止线程。在while循环中添加一个布尔标志,并在调用Stop()时将该标志设置为false。此停止标志与ReadTimeout相结合将确保您的程序最终退出。

如果正在执行的线程中止是在诸如捕获块之类的代码的受保护区域中,最终块或受约束的执行区域。如果线程calls Abort持有中止线程所需的锁,死锁可能发生。

我找到了一个解决方案当我取消从客户端发送时。。网络。DataAvailable设置为false。。所以我在服务器的接收方法中添加了这一行

在while循环中:

                while (sum < fileSize)
                {
                    if (network.DataAvailable)
                    {
                        count = network.Read(data, 0, data.Length);
                        fs.Write(data, 0, count);
                        sum += count;
                    }
                }

所以它永远不会卡在网络上。继续阅读。它完全工作