简体   繁体   English

暂停/恢复 C# 中的线程

[英]Pause/resume a thread in C#

I try to pause all my threads when I reach a certain value but I can't do it.当我达到某个值时,我尝试暂停所有线程,但我做不到。

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.我希望当我达到这个值时,所有线程都暂停 10 秒,然后在这 10 秒后所有线程重新启动。

I tried that with: Threads.Sleep();我试过了: Threads.Sleep(); | | Threads.Interrupt(); and Threads.Abort();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();
            }
        }

Here is an example of pausing some threads cooperatively, by using the PauseTokenSource + PauseToken pair from Stephen Cleary's AsyncEx.Coordination package.这是一个合作暂停一些线程的示例,使用来自 Stephen Cleary 的AsyncEx.Coordination package 的PauseTokenSource + PauseToken对。 This example shows also the use of the analogous CancellationTokenSource + CancellationToken pair, that inspired the creation of the aforementioned pausing mechanism.此示例还显示了类似的CancellationTokenSource + CancellationToken对的使用,这激发了上述暂停机制的创建。

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();

You may need to read this first, to get a grasp on the model used by the .NET platform for cooperative cancellation.您可能需要先阅读本文,以了解 .NET 平台用于协作取消的 model。 Cooperative "pausation" is very similar.合作“暂停”非常相似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM