Вопрос

У меня есть приложение для передачи файлов (сервер-клиент) ... при отправке файла я хочу включить отмену.
Client Отмена метода SendFile, который он работает на Projan Worker, он отправляет команду на сервер, чтобы отменить его приемную нить.

Когда сервер принимает эту команду, он вызывает, это вызывает способ остановки , но он застрял в этой строке network.read (данные, 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);
                }
            }
      }
.

Это было полезно?

Решение 3

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

Другие советы

Instead of aborting the thread, Close() the network. It will throw the exception like you are expecting.

Killing threads is a big no-no, since there are resources that can be left uncleaned...

NetworkStream.Read is blocked until it receives data. Set a timeout on the read operation by using NetworkStream's ReadTimeoutRead the community comment. Also, you may want to reconsider using Abort() to kill your thread. Add a boolean flag in your while loop, and set that flag to false when Stop() is called. This stop flag, combined with a ReadTimeout will ensure that your program eventually exits.

The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region. If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top