How to start a method in x seconds?

I am working on a C # Windows Forms application where I need a method to pause for 30 seconds until it moves to the next line of code. I tried Thread.Sleep() , which is not suitable for this application, and I realized that I should use some kind of timer instead. I searched a lot, but I can’t figure out how to implement timers.

My code is below and someone can show me how I should use the timer. I made a comment about 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(); } 
+10
c # timer
source share
6 answers

If your application is a .Net 4.5 application, then it is somewhat easier to use 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(); } 
+29
source share

Task.Delay is not available in .NET 4.0, but you can run a task that will just sleep for 30 seconds, and later you can continue working with the user interface thread:

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

At the class level, define an instance of Timer (there are several classes for this - for the winforms application you must use System.Windows.Forms.Timer )

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

Then in your method add lines to process your tick and run 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(); } 
+4
source share

There would also be a reactive extension mode:

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

We can do this using Task from

 System.Threading.Tasks.Task.Factory.StartNew(() => { Thread.Sleep(5000); this.Invoke(new Action(() => Method1())); }); 
0
source share
 System.Threading.Tasks.Task.Delay( 60 * 1000 ).ContinueWith( (_) => StartVoid() ); 
0
source share

All Articles