簡體   English   中英

無法正確停止C#中的所有線程

[英]Cannot stop properly all threads in c#

我正在嘗試在C#中使用token或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,檢查程序異常終止,不僅一次,而且可能在每個線程進程中都顯示。 如何顯示消息一次並同時停止所有線程? 我還要設置一些最大線程數,然后再繼續其他線程。 我嘗試了SetMaxThreads,但這似乎都不起作用。

請參考注釋以獲取最佳實踐建議,因為您在此處所做的操作並不完全正確,但是要實現您的目標,您可以使用帶有鎖的標志,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM