在 C# 中暂停/恢复线程 [英] Pause/resume a thread in C#

查看:98
本文介绍了在 C# 中暂停/恢复线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我达到某个值时,我尝试暂停所有线程,但我无法做到.

I try to pause all my threads when I reach a certain value but I can't do it.

我希望当我达到这个值时所有线程都暂停 10 秒,在这 10 秒后所有线程重新启动.

I would like that when I reach this value all threads are paused for 10 seconds and after these 10 seconds all threads start again.

我尝试过:Threads.Sleep(); |Threads.Interrupt();Threads.Abort(); 但没有任何作用.

I tried that with : Threads.Sleep(); | Threads.Interrupt(); and Threads.Abort(); but nothing work.

我尝试了您在下面代码中看到的内容.

I tried what you can see in the code below.

        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                Threads.Add(new Thread(new ThreadStart(example)));
                Threads[i].Start();
            }

            for (int i = 0; i < Threads.Count; i++)
                Threads[i].Join();
        }

        static void example()
        {           
            while (true)
            {
                Console.WriteLine(value++);
                checkValue();
            }
        }

        public static void checkValue()
        {
            if (value% 1000 == 0 && value!= 0)
            {
                for (int i = 0; i < Threads.Count; i++)
                    Threads[i].Interrupt();

                Thread.Sleep(1000);

                for (int i = 0; i < Threads.Count; i++)
                    Threads[i].Resume();
            }
        }

推荐答案

以下是使用 PauseTokenSource + PauseToken 对,来自 Stephen Cleary 的 AsyncEx.Coordination 包.此示例还显示了使用类似的 CancellationTokenSource + CancellationToken 对,启发前面提到的暂停机制.

Here is an example of pausing some threads cooperatively, by using the PauseTokenSource + PauseToken pair from Stephen Cleary's AsyncEx.Coordination package. This example shows also the use of the analogous CancellationTokenSource + CancellationToken pair, that inspired the creation of the aforementioned pausing mechanism.

var pts = new PauseTokenSource() { IsPaused = true };
var cts = new CancellationTokenSource();
int value = 0;

// Create five threads
Thread[] threads = Enumerable.Range(1, 5).Select(i => new Thread(() =>
{
    try
    {
        while (true)
        {
            cts.Token.ThrowIfCancellationRequested(); // self explanatory
            pts.Token.WaitWhilePaused(cts.Token); // ...and don't wait if not paused
            int localValue = Interlocked.Increment(ref value);
            Console.WriteLine($"Thread #{i}, Value: {localValue}");
        }
    }
    catch (OperationCanceledException) // this exception is expected and benign
    {
        Console.WriteLine($"Thread #{i} Canceled");
    }
})).ToArray();

// Start the threads
foreach (var thread in threads) thread.Start();

// Now lets pause and unpause the threads periodically some times
// We use the main thread (the current thread) as the controller
Thread.Sleep(500);
pts.IsPaused = false;
Thread.Sleep(1000);
pts.IsPaused = true;
Thread.Sleep(1000);
pts.IsPaused = false;
Thread.Sleep(1000);
pts.IsPaused = true;
Thread.Sleep(500);

// Finally cancel the threads and wait them to finish
cts.Cancel();
foreach (var thread in threads) thread.Join();

您可能需要阅读这个 首先,了解 .NET 平台用于协作取消的模型.合作暂停"非常相似.

You may need to read this first, to get a grasp on the model used by the .NET platform for cooperative cancellation. Cooperative "pausation" is very similar.

这篇关于在 C# 中暂停/恢复线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆