c# - 我怎样才能优雅地终止一个阻塞的线程?

标签 c# multithreading

有很多地方可以优雅地终止 C# 线程。但是,它们依赖于循环或在循环内执行的 if 条件,这假定该语句将被频繁执行;因此,当设置了 stop bool 标志时,线程会快速退出。

如果我有一个主题不是这样怎么办?在我的例子中,这是一个设置为从服务器接收数据的线程,该线程经常阻塞从输入流读取数据的调用,因为尚未提供任何数据,因此它会等待。

这是有问题的循环中的线程:

    while (true)
        {
            if (EndThread || Commands.EndRcvThread)
            {
                Console.WriteLine("Ending thread.");
                return;
            }

            data = "";
            received = new byte[4096];

            int bytesRead = 0;
            try
            {
                bytesRead = stream.Read(received, 0, 4096);
            }
            catch (Exception e)
            {
                Output.Message(ConsoleColor.DarkRed, "Could not get a response from the server.");
                if (e.GetType() == Type.GetType("System.IO.IOException"))
                {
                    Output.Message(ConsoleColor.DarkRed, "It is likely that the server has shut down.");
                }
            }

            if (bytesRead == 0)
            {
                break;
            }

            int endIndex = received.Length - 1;
            while (endIndex >= 0 && received[endIndex] == 0)
            {
                endIndex--;
            }

            byte[] finalMessage = new byte[endIndex + 1];
            Array.Copy(received, 0, finalMessage, 0, endIndex + 1);

            data = Encoding.ASCII.GetString(finalMessage);

            try
            {
                ProcessMessage(data);
            }
            catch (Exception e)
            {
                Output.Message(ConsoleColor.DarkRed, "Could not process the server's response (" + data + "): " + e.Message);
            }
        }

block 顶部的 if 语句执行正常的停止线程设置所做的事情:检查标志,如果已设置则终止线程。但是,通常会发现此线程在 stream.Read 处等待几行。

鉴于此,是否有任何方式可以优雅地终止此线程(即没有 Aborting),并清理其资源(有一个客户端需要关闭)?

最佳答案

假设您可以使用异步/任务,完全停止异步和 IO 操作的方法是使用连接到 CancelationTokenSourceCancelationToken。以下代码片段说明了将其应用于简化代码版本时的用法的简化示例。

class MyNetworkThingy 
{
    public async Task ReceiveAndProcessStuffUntilCancelled(Stream stream, CancellationToken token)
    {
        var received = new byte[4096];
        while (!token.IsCancellationRequested)
        {
            try
            {
                var bytesRead = await stream.ReadAsync(received, 0, 4096, token);
                if (bytesRead == 0 || !DoMessageProcessing(received, bytesRead))
                    break; // done.
            }
            catch (OperationCanceledException)
            {
                break; // operation was canceled.
            }
            catch (Exception e)
            {
                // report error & decide if you want to give up or retry.
            }
        }
    }

    private bool DoMessageProcessing(byte[] buffer, int nBytes)
    {
        try
        {
            // Your processing code.
            // You could also make this async in case it does any I/O.
            return true;
        }
        catch (Exception e)
        {
            // report error, and decide what to do.
            // return false if the task should not
            // continue.
            return false;
        }
    }
}

class Program
{
    public static void Main(params string[] args)
    {
        using (var cancelSource = new CancellationTokenSource())
        using (var myStream = /* create the stream */)
        {
            var receive = new MyNetworkThingy().ReceiveAndProcessStuffUntilCancelled(myStream, cancelSource.Token);
            Console.WriteLine("Press <ENTER> to stop");
            Console.ReadLine();
            cancelSource.Cancel();
            receive.Wait();
        }
    }
}

.

关于c# - 我怎样才能优雅地终止一个阻塞的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29422395/

相关文章:

c# - ASP.NET C# 验证用户名和密码

c# - 如何将 WorkItemCollection 转换为列表

c# - 如何提高方法的性能

python - 我如何在 Flask 的回调中返回 HTTP 响应,或者这是否重要?

multithreading - 在进程的线程之间共享信号量与在进程之间共享信号量有什么区别?

java - AtomicInteger 的映射

c# - LINQ to Entities 无法识别方法 IsNullOrWhiteSpace

java - 等待 future 的名单

java - Adapter.getView 从未被称为 Android Studio

c# - 无法检测到正确的字符编码