It looks to me as though you don't even need the BackgroundWorker
. Currently you have:
private void timer_Elapsed(object sender, EventArgs e)
{
TimerObject.Stop();
BackgroundWorker backgroundWorkerObject = new BackgroundWorker();
backgroundWorkerObject.DoWork += new DoWorkEventHandler(StartThreads);
backgroundWorkerObject.RunWorkerAsync();
TimerObject.Start();
}
private void StartThreads(object sender, DoWorkEventArgs e)
{
tasks = new Task[4];
tasks[0] = Task.Factory.StartNew(() => DoSomeLongWork());
tasks[1] = Task.Factory.StartNew(() => DoSomeLongWork());
tasks[2] = Task.Factory.StartNew(() => DoSomeLongWork());
tasks[3] = Task.Factory.StartNew(() => DoSomeLongWork());
// Give the tasks a second to start.
Thread.Sleep(1000);
}
All the BackgroundWorker
does is start threads and then for some unknown reason wait a second before continuing. I don't see any particular reason why you'd wait a second before letting the BackgroundWorker
exit.
If you remove that unnecessary delay, then you can change your code to:
private void timer_Elapsed(object sender, EventArgs e)
{
TimerObject.Stop();
tasks = new Task[4];
tasks[0] = Task.Factory.StartNew(() => DoSomeLongWork());
tasks[1] = Task.Factory.StartNew(() => DoSomeLongWork());
tasks[2] = Task.Factory.StartNew(() => DoSomeLongWork());
tasks[3] = Task.Factory.StartNew(() => DoSomeLongWork());
TimerObject.Start();
}
Another problem you have is that if those tasks don't complete before the timer elapsed event occurs again, you're going to overwrite the Tasks
array and your calculations (the Sum
array, in particular) will contain information from both sets of calculations. Your use of global variables here is going to get you in trouble if those threads take longer than five seconds to complete.
I'm going to assume that your DoSomeLongWork
method is just a placeholder, and won't critique that. I will mention, though, that there's no need to lock in order to increment a shared variable. Rather than:
int localIndex;
// lock the global variable from accessing by multiple threads at a time
lock (_countLock)
{
localIndex = Index;
Index++;
}
You can write:
localIndex = Interlocked.Increment(ref Index, 1) - 1;
Interlocked.Increment
increments the value atomically and returns the new value.