15

我正在用 C# 制作一个应用程序,它使用 winform 作为 GUI 和一个在后台运行的单独线程,自动改变事物。前任:

public void Run()
{
    while(true)
    {
        printMessageOnGui("Hey");
        Thread.Sleep(2000);
        // Do more work
    } 
}

我如何让它在循环中的任何地方暂停,因为循环的一次迭代大约需要 30 秒。所以我不想在它完成一个循环后暂停它,我想按时暂停它。

4

3 回答 3

30
var mrse = new ManualResetEvent(false);

public void Run() 
{ 
    while (true) 
    { 
        mrse.WaitOne();
        printMessageOnGui("Hey"); 
        Thread.Sleep(2000); . . 
    } 
}

public void Resume() => mrse.Set();
public void Pause() => mrse.Reset();
于 2010-03-12T07:02:04.203 回答
4

您应该通过ManualResetEvent执行此操作。

ManualResetEvent mre = new ManualResetEvent();
mre.WaitOne();  // This will wait

在另一个线程上,显然您需要参考 mre

mre.Set(); // Tells the other thread to go again

一个完整的例子,它将打印一些文本,等待另一个线程做某事然后恢复:

class Program
{
    private static ManualResetEvent mre = new ManualResetEvent(false);

    static void Main(string[] args)
    {
        Thread t = new Thread(new ThreadStart(SleepAndSet));
        t.Start();

        Console.WriteLine("Waiting");
        mre.WaitOne();
        Console.WriteLine("Resuming");
    }

    public static void SleepAndSet()
    {
        Thread.Sleep(2000);
        mre.Set();
    }
}
于 2013-07-04T15:32:54.983 回答
1

您可以通过调用来暂停线程,thread.Suspend但这已被弃用。我会看一下autoresetevent以执行您的同步。

于 2010-03-12T06:58:20.023 回答