C#|.NET : Generic Concurrent Queue (5/6)

First of all we will create an example task class (could be any model/view-model class), which is our real world class with the code to be processed on BG thread. The class encapsulates its own behavior.

This is a simple example class with a Name property and Process method. The process method has Debug messages and Thread.Join to simulate process. On completion of the process, the method fires an event on the dispatcher thread, i.e. the UI thread.

We will also need an equality comparer, to avoid duplicate objects being queued for process. Currently we will simply compare the reference, but equating could be extended in real world classes.

Now comes the implementation of our generic ConcurrentQueue class by inheriting in a new class named TaskOneQueue. We will implement the required method/properties in the derived class and in the ProcessRequest method, which is protected and called from the base class, we will call the TypeOneTask’s process method. This is the actual process which runs on the background thread. So here is the code for our TaskOneQueue:

We have our structure taken care of. Let’s put this things in a example form to see how things work. We will create a simple Windows Phone project and in the default MainPage.xaml’s ContentPanel element, we will put a StackPanel containing three buttons:

In the code above, we have defined TaskOneQueu type object – t1Queue. In Button_Click event handler we are enqueuing three TypeOneTasks and at the start and end of enqueuing, sending output to Debug window. This shows that UI thread gets free after enqueuing the tasks. This is further demonstrated in the click handlers of the buttonDummy1_Click and buttonDummy2_Click, which you can manually click at run time to see that UI thread is free and task processes are happening in the background. When we run this form in Debug mode, and click the first button and then subsequently Button 2 and Button 3 at 1-2 seconds apart, we get following output from Debug. You can see when UI thread gets free and first TypeOneTask starts processing. In the mean time the two dummy buttons are also clicked and their click events got registered successfully without having any impact on the background processes.