首页 > 解决方案 > 无法正确停止 c# 中的所有线程

问题描述

我正在尝试在 c# 中使用令牌或 thread.abort 停止所有线程,但两者都无法正常工作

                int workerThreads = 1;
                int portThreads = 0;

                ThreadPool.SetMinThreads(workerThreads, portThreads);
                ThreadPool.SetMaxThreads(workerThreads,portThreads);
                foreach (string d in list)
                {
                    var p = d;
                    ThreadPool.QueueUserWorkItem((c) =>
                    {
                        this.checker(p,cts.Token);
                    });
                }`

使用 checker 调用的函数构建如下:

    private void checker(string f, object obj)
    {
        try
        {
            CancellationToken token = (CancellationToken)obj;

            if (token.IsCancellationRequested)
            {
                MessageBox.Show("Stopped", "Checker aborted");
                token.ThrowIfCancellationRequested();
                cts = new CancellationTokenSource();
            } //etc main features of fucntion are hidden from here

当我调用 cts.Cancel(); 时,我想正确停止所有线程;但每次都会出现: Stopped , checker aborted 并且不仅是一次,而且可能会为每个线程进程显示。如何一次显示消息并在同一时刻停止所有线程?我还想设置一些在处理其他线程之前应该工作的最大线程数。我尝试使用 SetMaxThreads,但这似乎都不起作用。

标签: c#multithreadingtokenthreadpool

解决方案


请参阅评论以获取最佳实践建议,因为您在这里所做的并不完全正确,但为了实现您的目标,您可以使用标志与锁结合,如下所示:

private static object _lock = new object();
private static bool _stoppedNotificationShown = false;
private void checker(string f, object obj)
{
    try
    {
        CancellationToken token = (CancellationToken)obj;

        if (token.IsCancellationRequested)
        {
            lock(_lock) {
                if (!_stoppedNotificationShown) {
                    _stoppedNotificationShown = true;
                    MessageBox.Show("Stopped", "Checker aborted");
                }
            }
            token.ThrowIfCancellationRequested();
            cts = new CancellationTokenSource();
        } //etc main features of fucntion are hidden from here

推荐阅读