I have never had to use threads much – only a few occasions. But today, I was bored, and wanted to play with them… and try build an understanding. It looks like BackgroundWorkerThread is a good thing… So, I tried to make a console app that simply writes ‘Tick’ ever 5 seconds, 5 times. And this is what I came up with:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
BackgroundWorker bw = new BackgroundWorker();
AlarmClock ac = new AlarmClock(5);
bw.DoWork += ac.StartAlarm;
bw.RunWorkerAsync(5);
bool run = true;
while(run)
{
run = bw.IsBusy;
}
Console.WriteLine("Finished!!");
Console.WriteLine("Press a key...");
Console.ReadKey();
}
}
public class AlarmClock
{
private int noOfTicks;
public AlarmClock (int noOfTicks)
{
this.noOfTicks = noOfTicks;
}
public void StartAlarm(object sender, DoWorkEventArgs e)
{
DateTime start = DateTime.Now;
Console.WriteLine("Alarm set to tick ever 5 seconds.");
int ticks = 0;
bool runMe = true;
while (runMe)
{
if (DateTime.Now.Second % 5 == 0)
{
Console.WriteLine("Tick..");
ticks++;
Thread.Sleep(1000);
}
runMe = ticks < noOfTicks;
}
Console.WriteLine("Aboring thread.");
}
}
}
But it seems messy. Can anyone assist me to show me how it SHOULD be done?
As answered above, for the described case Timer is more efficient than BackgroundWorker. But if your goal is to learn how to work with BackgroundWorker class, you can do something like this: