Search code examples
c#cancellationthread-abort

Thread.Abort() stucks at NetworkStream.Read?


I have a file transfer application (server-client) ... while sending a file, i want to enable cancellation.
Client Cancel the SendFile method that it works by backgroundworker then it sends a command to the server to cancel its receiving thread.
when server receives this command it calls Stop method but it stucks in that line network.Read(data, 0, data.Length);

how can i abort this thread and go to finally without stucking in network.Read(..) ??
thanks in advance.

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);
                }
            }
      }

Solution

  • i've found a solution when i cancel sending from client side .. the network.DataAvailable set to false .. so i added this line to my receive method in the server

    in the while loop:

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

    so it will never stuck at network.Read anymore. it totally worked