【问题标题】:Pause/resume a thread in C#在 C# 中暂停/恢复线程
【发布时间】:2020-08-13 09:59:15
【问题描述】:

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

我希望当我达到这个值时,所有线程都暂停 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();
            }
        }

【问题讨论】:

  • 你试过SuspendResume方法吗?
  • 另外,如果可以选择协同暂停线程,请查看 Stephen Cleary 的 AsyncEx.Coordination 包中的 PauseTokenSource + PauseToken 对。
  • 我不明白 AsyncEX 是如何工作的。你能给我解释一下吗? @TheodorZoulias

标签: c# multithreading sleep resume pause


【解决方案1】:

这是一个合作暂停一些线程的示例,使用来自 Stephen Cleary 的 AsyncEx.Coordination 包的 PauseTokenSource + PauseToken 对。此示例还显示了类似的 CancellationTokenSource + CancellationToken 对的使用,即 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 平台用于协作取消的模型。合作“暂停”非常相似。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    相关资源
    最近更新 更多