14

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.

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

6 回答 6

32

如果您的应用程序是 .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();
}
于 2012-12-06T09:45:09.300 回答
13

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());
于 2012-12-06T09:43:48.867 回答
6

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

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

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

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();
}
于 2012-12-06T09:42:16.283 回答
4
System.Threading.Tasks.Task.Delay( 60 * 1000 ).ContinueWith( (_) => StartVoid() );
于 2019-09-18T20:03:07.913 回答
4

我们可以使用来自的任务来做到这一点

System.Threading.Tasks.Task.Factory.StartNew(() =>
        {
            Thread.Sleep(5000);
            this.Invoke(new Action(() => 
                Method1()));
        });
于 2018-06-06T11:08:00.503 回答
3

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

Observable.Return("Delayed").Delay(TimeSpan.FromSeconds(30)).Subscribe(val => Console.WriteLine("Executing delayed"));
于 2012-12-06T09:51:40.653 回答