Pause/resume C# 中的一个线程

Pause/resume a thread in C#

我尝试在达到某个值时暂停我的所有线程,但我做不到。

我希望当达到此值时所有线程都暂停 10 秒,然后在这 10 秒后所有线程再次启动。

我试过:Threads.Sleep(); | Threads.Interrupt();Threads.Abort(); 但没有任何效果。

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

        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 pair from Stephen Cleary's AsyncEx.Coordination package. This example shows also the use of the analogous CancellationTokenSource + CancellationToken pair, that inspired 上述暂停机制的创建。

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

您可能需要先阅读 this,以掌握 .NET 平台用于协作取消的模型。合作"pausation"很像。