Reputation: 966
I know this question has been asked quite a few times on SO, but none of them have been able to fix my problem. I want to call a function every 10 seconds using threads.
I have a function that does frame processing. I want to be able to grab a frame after every 10 seconds and then process it. My research showed that it would be best to use threads for that purpose, and, as I need to perform it after a specific period of time, I would also require a timer control.
I am not able to figure out how can use threading and timers together. Moreover, I have tried using a BackgroundWorker
control which, while processing, hangs up my app badly. I have also tried using a timer control and tried calling the function every 10 seconds, but in that case, if the process exceeds 10 seconds that might cause some problems.
Any examples or source code that could show me how to call a function every 10 seconds using threading will be really appreciated.
Upvotes: 3
Views: 22158
Reputation: 66783
You don't necessarily need threads. You can use await/async:
public async Task DoSomethingEveryTenSeconds()
{
while (true)
{
var delayTask = Task.Delay(10000);
DoSomething();
await delayTask; // wait until at least 10s elapsed since delayTask created
}
}
In this example, the returned task will never finish; to fix that you need to use some other condition instead of true
.
In an application with a GUI, this will execute DoSomething on the UI thread via the message loop, like any other event (like a button click handler). If there is no GUI, it will run on a thread pool thread.
Upvotes: 13
Reputation: 19
In a Windows Forms application, add a timer from Visual Studio's ToolBox, double-click it under the Designer view, and put the functionality that you want to be executed every X seconds in the function that appears. Be sure to enable the Timer in the properties view; there you can also change your interval (in milliseconds).
Upvotes: 0
Reputation: 29683
Use System.Windows.Forms.Timer
private Timer timer1;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 10000; // in miliseconds
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
yourfunctionhere();
}
Upvotes: 8