Ayaz Alifov

Ayaz Alifov

  • NA
  • 1
  • 1.9k

WPF multitasking along with a timer and background worker

Aug 30 2013 9:13 AM
Few days ago I started using tasks in my WPF application for parallelization purposes. My application needs to perform some work every 5 seconds. This work has to be parallelized by 4 tasks. And in addition to that the background worker needs to be implemented in order to avoid freezing of UI while doing the work by tasks. I found lots of examples to understand how tasks work. However, I couldn't find any simple examples to understand how tasks work along with timers, background worker and locks of course. I wrote some simple example to show you how I understood. Please, give me advises whether I do it correctly. By this way I will have better understanding in multitasking in WPF. I'm looking forward to your replies.


namespace timer_and_thread {
/// <summary> /// Interaction logic for MainWindow.xaml /// </summary>
public partial class MainWindow : Window
{

DispatcherTimer TimerObject;
Task[] tasks;

readonly object _countLock = new object();

int[] Summ = new int[10];

int Index = 0;

public MainWindow()

{

InitializeComponent();

TimerObject = new DispatcherTimer();

TimerObject.Tick += new EventHandler(timer_Elapsed);

TimerObject.Interval = new TimeSpan(0, 0, 5);

} // call the method every 5 seconds

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);
}

private void DoSomeLongWork()

{

while (Index < Summ.Length)

{

int localIndex = 0;

// lock the global variable from accessing by multiple threads at a time
lock (_countLock)

{
localIndex
= Index;

Index++;

}

//I wrote rundom number generation just a an example of doing some calculation and getting some result. It can also be some long calculation.

Random rnd = new Random();

int someResult = rnd.Next(1, 100000);

// lock the global variable (Summ) to give it the result of calculation

lock (_countLock)

{

Summ[localIndex] = someResult;

}

}

}

// button by which I start the application working

private void Start_Button_Click_1(object sender, RoutedEventArgs e)

{

TimerObject.Start();

}

}

}