C# 如何触发方法在 x 秒后运行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13740629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:39:22  来源:igfitidea点击:

How do I trigger a method to run after x seconds?

c#timer

提问by user1881847

I am working on a C# Windows Forms application where I need the method to pause for 30 seconds until it continues on to the next line of code. I have tried Thread.Sleep()which wasn't suitable for this application and I've understood that I should use some sort of timer instead. I have searched a lot but I can't figure out how to implement timers.

我正在处理一个 C# Windows 窗体应用程序,我需要该方法暂停 30 秒,直到它继续执行下一行代码。我试过Thread.Sleep()哪个不适合这个应用程序,我明白我应该使用某种计时器来代替。我搜索了很多,但我不知道如何实现计时器。

My code is below and could anyone show me how I should implement the timer. I have made a comment on where I want the method to pause.

我的代码在下面,任何人都可以告诉我应该如何实现计时器。我已经对我希望方法暂停的位置发表了评论。

private void start_Vid_Click(object sender, EventArgs e)
{
    if (video.State != StateFlags.Running)
    {
        viewport.Visible = true;
        video.Play();
    }

    //Here I want to wait 30 seconds until the next line of code is triggered

    viewport.Visible = false;
    viewport2.Visible = true;
    pictureBox1.Visible = true;
    start_Webc(); 
    video2.Play();
}

回答by Jamiec

At class level define an instance of Timer(There are a few classes like this - for a winforms app you should use System.Windows.Forms.Timer)

在类级别定义一个实例Timer(有几个这样的类 - 对于你应该使用的 winforms 应用程序System.Windows.Forms.Timer

static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();

Then in your method add lines to handle its tick and start it:

然后在你的方法中添加行来处理它的刻度并启动它:

private void start_Vid_Click(object sender, EventArgs e)
{
    if (video.State != StateFlags.Running)
    {
        viewport.Visible = true;
        video.Play();
    }

    myTimer.Tick += (o,ea) => {    
        viewport.Visible = false;
        viewport2.Visible = true;
        pictureBox1.Visible = true;
        start_Webc(); 
        video2.Play();
        myTimer.Stop();
    }
    myTimer.Interval = 5000; // 5 seconds
    myTimer.Start();
}

回答by Sergey Berezovskiy

Task.Delay is not available on .NET 4.0, but you can start task, which will just sleep for 30 seconds, and later you can continue on UI thread again:

Task.Delay 在 .NET 4.0 上不可用,但您可以启动任务,它只会休眠 30 秒,然后您可以再次在 UI 线程上继续:

Task.Factory.StartNew(() => Thread.Sleep(30 * 1000))
            .ContinueWith((t) =>
    {
         viewport.Visible = false;
         viewport2.Visible = true;
         pictureBox1.Visible = true;
         start_Webc(); 
         video2.Play();
    }, TaskScheduler.FromCurrentSynchronizationContext());

回答by Kamyar Nazeri

If your app is a .Net 4.5 application, then it's somewhat easier to use Task:

如果您的应用程序是 .Net 4.5 应用程序,那么使用起来会更容易一些Task

private async void start_Vid_Click(object sender, EventArgs e)
{
    if (video.State != StateFlags.Running)
    {
        viewport.Visible = true;
        video.Play();
    }

    await Task.Delay(TimeSpan.FromSeconds(30));

    viewport.Visible = false;
    viewport2.Visible = true;
    pictureBox1.Visible = true;
    start_Webc();
    video2.Play();
}

回答by LaurinSt

There would also be a way with reactive extensions:

还有一种反应式扩展的方法:

Observable.Return("Delayed").Delay(TimeSpan.FromSeconds(30)).Subscribe(val => Console.WriteLine("Executing delayed"));

回答by Mahesh

We can do that using Task from

我们可以使用 Task from

System.Threading.Tasks.Task.Factory.StartNew(() =>
        {
            Thread.Sleep(5000);
            this.Invoke(new Action(() => 
                Method1()));
        });

回答by Erik

System.Threading.Tasks.Task.Delay( 60 * 1000 ).ContinueWith( (_) => StartVoid() );