There are actually couple of ways to achieve such goal.
There are couple of ways - using Timer
, Thread
or Task
.
I won't focus on Thread
as it's "old" approach to code parallelization and I try to avoid it. Task
is the way to go in most cases and I will present that approach.
Without further ado, below is the code, with three methods, each containing different solution to your problem. Each has rich comment to explain what and how:
public class DoStuffPeriodically
{
const int intervalMs = 300;
public static void DoStuff() { }
// Here you "do stuff", wait 300 ms and repeat the loop
// after completion.
// NOTE: DoStuff does not happen every 300ms, the timeline is:
// do stuff (for some milliseconds, maybe 100), wait 300ms and repeat.
// So another DoStuff will begine 400ms after first.
public static async Task FirstApproach()
{
while (true)
{
DoStuff();
await Task.Delay(intervalMs);
}
}
private static readonly List<Task> tasks = new List<Task>();
// Here you "do stuff" in a Task, which allows not waiting for it,
// but storing reference to "that processing" and await it later.
// NOTE: DoStuff does happens every 300ms, the timeline is:
// start doing stuff and immediiately wait 300ms and repeat.
public static async Task SecondApproach()
{
while (true)
{
tasks.Add(Task.Run(DoStuff));
await Task.Delay(intervalMs);
}
// remember to await all the remaining tasks in "tasks" array.
await Task.WhenAll(tasks);
}
// Using a timer, classic approach.
public static void ThirdApproach()
{
// Create a timer with a two second interval.
var aTimer = new System.Timers.Timer(intervalMs);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += (o, e) => DoStuff();
aTimer.AutoReset = true;
aTimer.Enabled = true;
// Here code execution continues, you have to block the program
// from running to completion to keep timer alive, for example
// in console app you could do this:
Console.WriteLine("\nPress the Enter key to exit the application...\n");
Console.ReadLine();
// After using timer, stop it and dispose it.
aTimer.Stop();
aTimer.Dispose();
}
}
Convert.ToDouble(300).miliseconds
makes no sense, missing parenthesis, no matching overload, etc.). You also don't show what you do in the timer.