Monday, April 25, 2011

Array of WaitHandles (ManualResetEvent, AutoResetEvent, …) when waiting for operations to complete …

Reference :- http://blog.cincura.net/231837-array-of-waithandles-manualresetevent-autoresetevent-when-waiting-for-operations-to-complete/

Often, when you discover the beauty of multithreading and parallelism, you find a need to run some operations in parallel and wait for completion. Fairly common scenario. Although now, with .NET Framework 4, you can write it using Task Parallel Library‘s Parallel.Invoke, there are scenarios when you need to plug it in into some other methods/parameters, so you’ll do it yourself explicitly with threads or better to say ThreadPool.

The method I see from time to time looks basically like this:



Though it’s not wrong, except the ManualResetEvents are not Disposed, it’s suboptimal. You’re wasting resources creating array of these objects.

But if you think about it, you can write it better. Better in a way for scaling, performance and memory consumption.




I’m simply using one synchronization object (and using using statement ), because I’m really interested in only when all tasks are done (one stuff), and decrementing the total number of tasks every time one finishes. Using Interlocked class I’m sure no race condition will occur and I’ll get the right results. After it reaches zero I’m signaling I’m done and the method can continue.

Fewer resources, atomic operations usage … better/faster results.

Saturday, April 23, 2011

WPF Timer (DispatcherTimer)

Reference :- http://www.dotnetspider.com/resources/29705-WPF-Timer-DispatcherTimer.aspx

Most of us are from a background of C# (or VB.Net). You must have some point of time come across a scenario for performing a repetitive GUI operation after certain period of time. The solution in most cases has been the WinForm's Timer.


What about WPF ? Does it have a Timer ?

WPF no different to WinForm has it's own Timer equivalent. It is called DispatcherTimer. There are other options to get the Timer behavior but one of the most efficient for a Window based operation is the DispatcherTimer.

I have attached a sample Timer application demonstrating the functionality.
The window has a "Start timer" and "Stop timer" functionality. There is an input TextBox which takes the Timer frequency in milliseconds.

Just enter the Timer frequency in millisecond and hit the "Start timer" button. There is a status bar which displays the status of the time. At start it will be blank. When you start the Timer it will display the current Time and when you stop the Timer it will display the "Stopped" status.

Let us discuss the code to look into how we use it.

XAML,

< Window x:Class="TimerSample.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Timer" Height="148" Width="300" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">

1000 Not working

Code behind,

public partial class Window1 : Window{ DispatcherTimer _timer; public Window1() { InitializeComponent(); _timer = new DispatcherTimer(); _timer.Tick += new EventHandler(delegate(object s, EventArgs a) { status.Text = "Started: " + DateTime.Now; //MessageBox.Show("Dummy message"); //notify timer end //this.Close(); //close application }); } private void Start_Click(object sender, RoutedEventArgs e) { // Set the Interval _timer.Interval = TimeSpan.FromMilliseconds(Convert.ToDouble(time.Text)); // Start the timer _timer.Start(); status.Text = "Started"; } private void Stop_Click(object sender, RoutedEventArgs e) { // Stop the timer _timer.Stop(); status.Text = "Stopped"; }}

We have a local variable of type DispatcherTimer - _timer. We manipulate this variable to start and stop the timer. At start we initialize the variable with an Event delegate to fire whenever the Timer ticks.

_timer.Tick += new EventHandler(delegate(object s, EventArgs a) { status.Text = "Started: " + DateTime.Now; //MessageBox.Show("Dummy message"); //notify timer end //this.Close(); //close application });

I have specifically left the commented lines to show the different possibilities that can be done in the Event delegate. Whenever the Timer ticks the event is fired and Status bar is updated with the most recent DateTime.

DispatcerTimer runs on the UI thread and hence does not need marshaling back and forth as we have to do in the normal cases of a Thread.