Tuesday, December 28, 2010

WPF - Interprocess Messaging using Memory Mapped Files

.Net framework 4.0 has a I/O based mechanism to exchange data between processes. It is Memory-mapped files. The idea is to create an in-memory file and use that file as a means of communication of messages between different processes.



Let us create a sample WPF application. This just writes the contents of user-entered data to a named memory-mapped file. This also reads data from the file and shows in a text block. Let us name this as WpfApplication_MemoryMappedFiles.

Open MainWindow.xaml and update it as follows:

<Window x:Class="WpfApplication_MemoryMappedFiles.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Height="30" HorizontalAlignment="Left" Margin="12,22,0,0" Name="textBoxDataTo"
VerticalAlignment="Top" Width="337" />
<Button Content="Write Data" Height="28" HorizontalAlignment="Left" Margin="12,58,0,0"
Name="btnWriteData" VerticalAlignment="Top" Width="143" Click="btnWriteData_Click" />
<TextBlock Height="81" HorizontalAlignment="Left" Margin="12,92,0,0" Name="textBlockDataFrom"
Text="TextBlock For Data Read from Memory Mapped File" VerticalAlignment="Top" Width="337" />
<Button Content="Read Data" Height="29" HorizontalAlignment="Left" Margin="12,0,0,103"
Name="btnReadData" VerticalAlignment="Bottom" Width="142" Click="btnReadData_Click" />
</Grid>
</Window>

Let us update the code behind of the above window as follows:

public partial class MainWindow : Window
{
MemoryMappedFile memoryMappedFileMediator;
MemoryMappedViewAccessor memoryMappedFileView;

public MainWindow()
{
InitializeComponent();

memoryMappedFileMediator = MemoryMappedFile.CreateNew("MediatorMemoryMappedFile", 1000, MemoryMappedFileAccess.ReadWrite);
memoryMappedFileView = memoryMappedFileMediator.CreateViewAccessor();
}

private void btnWriteData_Click(object sender, RoutedEventArgs e)
{

byte[] message = Encoding.UTF8.GetBytes(this.textBoxDataTo.Text);
memoryMappedFileView.Write(0, message.Length);
memoryMappedFileView.WriteArray<byte>(4, message, 0, message.Length);
memoryMappedFileView.Flush();

}

private void btnReadData_Click(object sender, RoutedEventArgs e)
{
byte[] message = new byte[memoryMappedFileView.ReadInt32(0)];
memoryMappedFileView.ReadArray<byte>(4, message, 0, message.Length);
string tempMessage = Encoding.UTF8.GetString(message, 0, message.Length);


this.textBlockDataFrom.Text = tempMessage;
}
}

We need to add the namespace using System.IO.MemoryMappedFiles in order to build the above code. This namespace has the required memory mapped files related types defined. We are just writing the length of data in the file followed by the data starting from a specified position in the file. We would start reading the data from the same position when we would read the file. The length of data in the beginning avoids making unnecessary guess about the length of data. This is purely a choice how we want to define the length of our messages.

Let us run the project. We enter "WPF Rocks!!!" in the text box and hit "Write Data" button. As we click Read Data button, the data is read from the memory mapped file and updates the text box as follows:



Inter-process messaging:
In order to present the idea of communication of messages between different processes, let us create a new WPF application named MemoryMappedFile_MessageRecipient. Let us update the xaml of MainWindow as follows:

<Window x:Class="MemoryMappedFile_MessageRecipient.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock Height="196" HorizontalAlignment="Left" Margin="6,6,0,0" Name="textBlockMessage"
Background="Beige" VerticalAlignment="Top" Width="488" />
<Button Content="Get Data" Height="33" HorizontalAlignment="Left" Margin="8,210,0,0"
Name="btnReadMessage" VerticalAlignment="Top" Width="172" Click="btnReadMessage_Click" />
</Grid>
</Window>

This just has a text block and a button. Clicking the button should update the TextBlock with the message read from memory mapped file. The code behind is as follows:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void btnReadMessage_Click(object sender, RoutedEventArgs e)
{
using (MemoryMappedFile memoryMappedFileMediator = MemoryMappedFile.OpenExisting("MediatorMemoryMappedFile"))
{
using (MemoryMappedViewAccessor memoryMappedFileView = memoryMappedFileMediator.CreateViewAccessor())
{
byte[] message = new byte[memoryMappedFileView.ReadInt32(0)];
memoryMappedFileView.ReadArray<byte>(4, message, 0, message.Length);
string tempMessage = Encoding.UTF8.GetString(message, 0, message.Length);


this.textBlockMessage.Text = tempMessage; //tempMessage.Substring(0, tempMessage.IndexOf("!!!") + 3);
}
}
}
}

Here we have used the same protocol as defined in previous example. We are reading the length of message from the beginning of the file. We are expecting the message afterwards.

Now let us run both application together. We first bring the first application up and write "Pakistan Zindabad!" to the memory mapped file. In order to verify that the message is written to the memory mapped file. We click the Read Data button. The form should read the contents of the memory mapped file and update the contents of the TextBlock.



Keeping this running, let us bring the second application (MemoryMappedFile_MessageRecipient). Click Read Data button. The contents of the window should be updated as follows:



Limitations:
Only value types can be used with a Memory-mapped file. It also supports arrays and structs of the value-types.

Length of Message:
When a recipient reads a message from a Memory-mapped file, it has to specify the length of data to read from this. The issue is how the recipient would know the length of data in advance. I have seen people using many techniques:

1. Write the length of message in the beginning. It specifies the length of characters to read from the memory mapped file.

2. Write only fixed length data to the memory mapped file. If the contents are smaller then append it with some known characters. Get rid of the appended data at the end of the message.

Securing Memory Mapped file:
As discussed, the memory mapped file is created in memory. Now this is the same memory shared by all the processes. You might be thinking about securing your message or some how tunnel it so, even if, someone peek into it, it just couldn't understand the message.

Is really a file created?
When we are creating memory-mapped files just for the purpose of sharing data between processes. Sometimes, it seems to be a misnomer in this case as we are not creating any physical file. It is rather setting aside a named memory space for sharing of data between two processes.

Memory mapped file for random I / O:
We have discussed memory-mapped file as a mechanism for sharing data between processes. Memory mapped file is much more than that. It allows to provide random access to a data in a file. If we need to update the contents of file on a very frequent basis at random basis, we can create a memory-mapped file from that file. Work with memory mapped file for the whole operation. Un-map the memory-mapped file saving the original file.

This is basically 10 times faster for random access of file data than FileStream.

File Not Found Exceptions:
If we attempt to open a non-existing memory-mapped file then it results in the familiar File Not Found Exception.



Lifetime of memory mapped file:
As we know that MemoryMappedFile available in .net 4.0 implements IDisposable. After disposing, all the references to the memory mapped file are lost. It doesn't mean that memory mapped file is scrapped by Windows. Windows keeps the file up even if there is one reference to the file by any process. If the number of references to the memory mapped file are ZERO, then it is claimed by the operating system. You would find the attached code similar to this concept. In order to prove this point, follow these steps:

1. Bring the WpfApplication_MemoryMappedFiles up and write some data to the memory mapped file (e.g. "Message from app1")

2. Bring the MemoryMappedFile_MessageRecipient application up. Read data from the memory mapped file.

3. Turn the application (step 1) down. Bring it back up and click Read Data button. You would notice that the same data is read into the TextBlock.

4. Now bring both applications down. Bring the first application (step 1) up and read data from memory mapped file by clicking "Read Data" button. No data is read.

This proves our point that as long as there is one reference to the memory mapped file, the resource is not claimed by Windows.

Download:

Saturday, December 25, 2010

WPF - EventAggregator in PRISM 4.0 (CAL)

Since the last few posts, I have started discussing about different signaling and messaging options available for decoupled components. This is a continuation of this series of posts. Prism has been a priority option for big scale WPF / Silverlight projects. Microsoft keeps updating it with new technology features introduced in the framework. In november this year, Version 4.0 is released for the product. It has a big feature set of developing rich applications on both desktop / web platforms.

Although there are a number of components available with the framework. We can pick and choose the components we want. We have seen people calling the adoption of PRISM is difficult. It is difficult because there is a certain prerequisite knowledge required to choose components of PRISM or using PRISM in totality. You have to have knowledge about Commands, Message Bus, MVVM, Unity, MEF in order to get started with the framework. This becomes a little easier by providing this opt-in model for features.

It must be remembered that PRISM is designed for large applications with lots of different teams working on different modules decoupled from each other. Microsoft has never claimed it to be used for small scale applications. When you start using PRISM, you have this feel of developing large scale applications the right way as it seems to be scalable.

In this post, we are discussing EventAggregator feature of Prism. I don't know who coined this term. But the first article that I see about this topic is by Martin Fowler [http://martinfowler.com/eaaDev/EventAggregator.html]. This article still shows up as Work In Progress.

When we see the name of event associated with this. We think about memory leaks. We This is generally not true with EventAggregator as it uses WeakReference by default for messages publishing and subscription.

You can download Prism from here:
http://compositewpf.codeplex.com/

To use EventAggregator feature from Prism 4.0, we just need to add the reference of Microsoft.Practices.Prism library. You can find it in the above download location.



We just need to use EventAggregator and CompositePresentationEvent from this library. Both are available in Microsoft.Practices.Prism.Events namespace.

Let us create a separate Services class so that the same Message Bus is available across the application. As you can see you can define a number of Message Buses in an application for intra / inter - module message passing.

class Services
{
public static EventAggregator MessageBus { get; private set; }

static Services()
{
MessageBus = new EventAggregator();
}
}

Now we define the messages that we are wishing to pass using Message Bus. All the interested parties can subscribe / publish events by specifying the exact type. This makes the design robust as there are no run-time surprises for different modules. The messages are inherited from CompositePresentationEvent generic type.

public class ServiceShutDown : CompositePresentationEvent<ShutDownDetails> { }

As seen above CompositePresentationEvent is a generic type. The definition of ShutdownDetails is as follows:
public class ShutDownDetails
{
public string ShutDownMessage { get; set; }
}

This is all the plumbing code we need to use EventAggregator in our applications. Now we can publish and subscribe ServiceShutDown events from anywhere in the application.

Let us define our MainWindow. It just has two buttons to open two separated Window.

<Window x:Class="WPF_Prism_EventAggregator_Example.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="266" Width="359">
<Grid>
<Button Content="Open Another Window" Height="56" HorizontalAlignment="Left"
Margin="12,61,0,0" Name="button1" VerticalAlignment="Top" Width="313" Click="button1_Click" />
<Button Content="Open Shutdown Window" Height="55" HorizontalAlignment="Left" Margin="12,133,0,0"
Name="button2" VerticalAlignment="Top" Width="311" Click="button2_Click" />
</Grid>
</Window>

The code behind of the above window is as follows:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

Services.MessageBus.GetEvent<ServiceShutDown>().Subscribe((details) =>
{
MessageBox.Show(details.ShutDownMessage);
this.IsEnabled = false;
});
}

private void button1_Click(object sender, RoutedEventArgs e)
{
new AnotherWindow().Show();
}

private void button2_Click(object sender, RoutedEventArgs e)
{
new WindowShutDown().Show();
}
}

In the constructor, we are registering with the MessageBus for ServiceShutDown event. This allows us to define a callback. Here the callback is defined as a lambda. We are just showing the shut down message available in the event and disabling the Window.

There are two more windows used in the above MainWindow.

AnotherWindow:

<Window x:Class="WPF_Prism_EventAggregator_Example.AnotherWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="537">
<Grid>

</Grid>
</Window>

This has no controls in it. The main piece of interest is the code behind. Here we are subscribing to the same shut down event. We are just closing the Window as we receive this message.

public partial class AnotherWindow : Window
{
public AnotherWindow()
{
InitializeComponent();

Services.MessageBus.GetEvent<ServiceShutDown>().Subscribe((details) =>
{
this.Close();
});
}
}

WindowShutDown:

<Window x:Class="WPF_Prism_EventAggregator_Example.WindowShutDown"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WindowShutDown" Height="300" Width="300">
<Grid>
<Button Content="Shut Down" Height="59" HorizontalAlignment="Left"
Margin="22,88,0,0" Name="button1" VerticalAlignment="Top" Width="237" Click="button1_Click" />
</Grid>
</Window>

As we click the button, we send the shut down message and closes itself. The code behind is as follows:

public partial class WindowShutDown : Window
{
public WindowShutDown()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
Services.MessageBus.GetEvent<ServiceShutDown>().Publish(new ShutDownDetails()
{
ShutDownMessage = "Disconnected..."
});
this.Close();
}
}

Now we run the application and click both buttons on the Main window. This opens the corresponding windows.



As we click the Shut Down button on the WindowShutdown, shut down message is published on the Message Bus (EvenAggregator). Since MainWindow and AnotherWindow is subscribed to the Message, they receive this event and do the needful.

The following message box is displayed from the MainWindow.



After user clicks OK on the MessageBox, MainWindow is disabled.



Threading Options for EventAggregator messages
PRISM allows us to subscribe to messages. It allows that these messages are received in Publisher's or just any background thread. We can also specify that messages are received in UIThread. If we do it like that, we don't need to dispatch messages to the UI thread.



Weak Reference Vs Live Reference:
By default the EventAggregator events are subscribed with weak reference. EventAggregator also supports subscribing with LiveReference, we just have to use an overload of Subscribe method and specify true for this parameter.

Services.MessageBus.GetEvent<ServiceShutDown>().Subscribe((details) =>
{
MessageBox.Show(details.ShutDownMessage);
this.IsEnabled = false;
}, true);

Please don't forget to unsubscribe from the Message when you are done with it, in order to avoid any memory leaks in your system.

Filtered Messages:
Some messages are very generalized. Message might have various fields. We can subscribe to an event but only interested in receiving messages which fulfills a certain criteria. We can specify this criterion by providing predicates when these events are subscribed.

Thursday, December 23, 2010

WPF - Thread Synchronization using Barrier

In this post, we will be discussing about a new Thread Signaling construct available in .net 4.0. This signaling construct is Barrier. It basically allows participating threads to work in phases in synchronization. After signaling, the barrier blocks the threads from execution until all participating threads have signaled. As all signals are received, it performs a post-blocking action. As soon as the post-blocking action is finished, all participating threads can resume their operation.

We discussed CountdownEvent in the previous post. It must be remembered that both of these signaling constructs are introduced with .net 4.0. Though CountdownEvent also depends upon signaling of a certain number of threads but it does not block them after they signal until we explicitly call Wait afterwards [http://msdn.microsoft.com/en-us/library/system.threading.countdownevent.wait.aspx]. The other difference is that a thread can only signal once at one time for barrer. Alternatively, CountdownEvent can generate two signals by using overloads of Signal method available.

This seems to be very disciplined construct. The example of this feature should be form an environment which is also very disciplined. Let us take the example of an army mission. A team of 4 army-men are formed to attack an enemy land. The team consists of three soldiers and their commander. Each soldier has to secure a position and signal the commander. When all soldiers have signaled, the commander runs all procedures and orders the attack. In order to keep the example simple, we are discussing this one phase, otherwise, we can also extend this example for other posts in the enemy land. We can also update it to include the provision of reducing the number of participants when a soldier is down.



The form should appear as follows:



Clicking each button should update the display about the ready position of the soldier. When all buttons are clicked, the commander notification text box is udpated as "Attack!!!".

This window is designed as follows:

<Window x:Class="WpfApplication_Barrier.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="T1 ready to attack" Height="31" HorizontalAlignment="Left" Margin="16,53,0,0"
Name="btnT1" VerticalAlignment="Top" Width="156" Click="btnT1_Click" />
<Button Content="T2 ready to attack" Height="31" HorizontalAlignment="Left" Margin="16,100,0,0"
Name="btnT2" VerticalAlignment="Top" Width="156" Click="btnT2_Click" />
<Button Content="T3 ready to attack" Height="31" HorizontalAlignment="Left" Margin="16,144,0,0"
Name="btnT3" VerticalAlignment="Top" Width="156" Click="btnT3_Click" />
<TextBlock Height="46" HorizontalAlignment="Left" Margin="260,24,0,0"
Name="txtNotificationCommander" Text="Commander Waiting..." VerticalAlignment="Top" Width="231" />
<TextBlock Height="29" HorizontalAlignment="Left" Margin="197,55,0,0"
Name="textBlockT1AttackNotification" Text="" VerticalAlignment="Top" Width="194" />
<TextBlock Height="25" HorizontalAlignment="Left" Margin="197,100,0,0" Name="textBlockT2AttackNotification"
Text="" VerticalAlignment="Top" Width="196" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="194,152,0,0" Name="textBlockT3AttackNotification"
Text="" VerticalAlignment="Top" Width="201" />
</Grid>
</Window>

The code behind of the window is as follows:

public partial class MainWindow : Window
{
static Barrier _barrier;
public MainWindow()
{
InitializeComponent();

_barrier = new Barrier(3, (a) =>
{
this.Dispatcher.BeginInvoke(new Action(() =>
this.txtNotificationCommander.Text = "Running SOP for attack..."));

Thread.Sleep(5000);

this.Dispatcher.BeginInvoke(new Action(() =>
this.txtNotificationCommander.Text = "Attack!!!"));
}
);

}

private void btnT1_Click(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
this.Dispatcher.BeginInvoke(new Action(() =>
this.textBlockT1AttackNotification.Text = "T1 ready Sir!"));

_barrier.SignalAndWait();

this.Dispatcher.BeginInvoke(new Action(() =>
this.textBlockT1AttackNotification.Text = "T1 attacks!"));
}
).Start();
}

private void btnT3_Click(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
this.Dispatcher.BeginInvoke(new Action(() =>
this.textBlockT3AttackNotification.Text = "T3 ready Sir!"));

_barrier.SignalAndWait();

this.Dispatcher.BeginInvoke(new Action(() =>
this.textBlockT3AttackNotification.Text = "T3 attacks!"));
}
).Start();
}

private void btnT2_Click(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
this.Dispatcher.BeginInvoke(new Action(() =>
this.textBlockT2AttackNotification.Text = "T2 ready Sir!"));
_barrier.SignalAndWait();

this.Dispatcher.BeginInvoke(new Action(() =>
this.textBlockT2AttackNotification.Text = "T2 attacks!"));
}
).Start();

}
}

When we click button 1, a signal is generated by T1. The thread is blocked after this until barrier allows it.
new Thread(() =>
{
this.Dispatcher.BeginInvoke(new Action(() =>
this.textBlockT1AttackNotification.Text = "T1 ready Sir!"));

_barrier.SignalAndWait();

this.Dispatcher.BeginInvoke(new Action(() =>
this.textBlockT1AttackNotification.Text = "T1 attacks!"));
}
).Start();



Now click the second button. This would cause T2 to start blocking.

new Thread(() =>
{
this.Dispatcher.BeginInvoke(new Action(() =>
this.textBlockT2AttackNotification.Text = "T2 ready Sir!"));
_barrier.SignalAndWait();

this.Dispatcher.BeginInvoke(new Action(() =>
this.textBlockT2AttackNotification.Text = "T2 attacks!"));
}
).Start();



Now click third button. This would create a new thread and signal the barrier.

new Thread(() =>
{
this.Dispatcher.BeginInvoke(new Action(() =>
this.textBlockT3AttackNotification.Text = "T3 ready Sir!"));

_barrier.SignalAndWait();

this.Dispatcher.BeginInvoke(new Action(() =>
this.textBlockT3AttackNotification.Text = "T3 attacks!"));
}
).Start();



Now look at the definition of barrier, _barrier. Since all signals are received, it can run the post-phase action. In this case, we are just using Thread.Sleep() to simulate any work done by the thread.

_barrier = new Barrier(3, (a) =>
{
this.Dispatcher.BeginInvoke(new Action(() =>
this.txtNotificationCommander.Text = "Running SOP for attack..."));

Thread.Sleep(5000);

this.Dispatcher.BeginInvoke(new Action(() =>
this.txtNotificationCommander.Text = "Attack!!!"));
}
);



The form is updated as follows:



When the action is finished execution, all threads are signaled to unblock themselves. In our example, they just update the form with new text.





You can see that how easily we have implemented this complex logic which involved the working of a bunch of threads in synchronization.

Wednesday, December 22, 2010

WPF - Notification through Thread Signaling constructs

In this post, we will be discussing how we can use EventWaitHandle to signal between different windows. We will also see how the same logic applies to signal between different processes. We will find how we can consume these notifications using regular threads and ThreadPool’s WaitHandle registration features. In the later part, we will be touching on CountdownEvent which is a new feature in .net 4.0.

Let us create a sample application. It has two kind of windows. One window would serve as Server Window. It has a responsibility of generating notifications for different parts in the same window or across different windows in the same or different processes.



It has three buttons and a textual notification. Signal button would give notification to the interesting thread created by the same window. Open another window opens a new window for consumption of signals. Signal another window generates notifications for the other window. The XAML for the above window is as follows:

<Window x:Class="WpfApplicationA_Signaling.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Signal" Height="35" HorizontalAlignment="Left"
Margin="23,129,0,0" Name="btnSignalSet" VerticalAlignment="Top" Width="147" Click="btnSignalSet_Click" />
<Label Content="Waiting for signal..." Height="38" HorizontalAlignment="Left" Margin="220,125,0,0"
Name="LabelStatus" VerticalAlignment="Top" Width="196" />
<Button Content="Open another window" Height="39" HorizontalAlignment="Left" Margin="23,184,0,0"
Name="button1" VerticalAlignment="Top" Width="147" Click="button1_Click" />
<Button Content="Signal another window" Height="39" HorizontalAlignment="Left" Margin="227,184,0,0"
Name="button2" VerticalAlignment="Top" Width="189" Click="button2_Click" />
</Grid>
</Window>

The code behind for this is as follows:

public partial class MainWindow : Window
{
static EventWaitHandle _waitHandle = new AutoResetEvent(false);

EventWaitHandle _waitHandleNamed = new EventWaitHandle(false, EventResetMode.ManualReset, "MyWaitHandle");

public MainWindow()
{
InitializeComponent();

new Thread(() =>
{
_waitHandle.WaitOne();

this.Dispatcher.BeginInvoke(new Action(() => this.LabelStatus.Content = "Signal received1"));
}

).Start();

new Thread(() =>
{
_waitHandle.WaitOne();
this.Dispatcher.BeginInvoke(new Action(() => this.LabelStatus.Content = "Signal received2"));
}
).Start();
}

private void btnSignalSet_Click(object sender, RoutedEventArgs e)
{
_waitHandle.Set();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
new OtherWindow().Show();
}

private void button2_Click(object sender, RoutedEventArgs e)
{
_waitHandleNamed.Set();
}
}

In the above code, we are creating an AutoResetEvent, named _waitHandle. In the constructor, we are waiting for this EventWaitHandle in two different threads by calling WaitOne on this EventWaitHandle. As soon as the thread is notified, we are setting the content of LabelStatus as Signal received1 for first thread and Signal received2 for second thread. When the constructor ends, two threads are ready to receive notification. As soon as they would receive the signal, they can resume their operation.

new Thread(() =>
{
_waitHandle.WaitOne();

this.Dispatcher.BeginInvoke(new Action(() => this.LabelStatus.Content = "Signal received1"));
}
).Start();


new Thread(() =>
{
_waitHandle.WaitOne();
this.Dispatcher.BeginInvoke(new Action(() => this.LabelStatus.Content = "Signal received2"));
}
).Start();




Since this is an AutoResetEvent, each thread would wait for its turn. A signal is received by only one. This one is generally the one at the top of the queue.

Now run the application. Click on Signal button. The first thread in the queue gets the signal. This thread now can resume its operation and updates the Label Status as Signal received1.



Now hit the Signal button again. Now second thread gets the notification and updates the LabelStatus as Signal received2.



You might have noticed (in the event handler for Click event for button1, button1_Click), we are showing OtherWindow. The OtherWindow is defined as follows:

<Window x:Class="WpfApplicationA_Signaling.OtherWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="OtherWindow" Height="300" Width="300">
<Grid>
<TextBlock Height="31" HorizontalAlignment="Left" Margin="8,63,0,0"
Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" Width="261" />
</Grid>
</Window>

The code behind for this window is as follows:

public partial class OtherWindow : Window
{
EventWaitHandle _waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, "MyWaitHandle");

public OtherWindow()
{
InitializeComponent();

new Thread(() =>
{
_waitHandle.WaitOne();
this.Dispatcher.BeginInvoke(new Action(() => this.textBlock1.Text = "Signal received"));
}
).Start();
}
}

In this window _waitHandle is the similar EventWaitHandle as in MainWindow. This is a ManualReset type of EventWaitHandle. The name of event is “MyWaitHandle”. Like MainWindow’s, here we are starting a new thread which is waiting for this EventWaitHandle. It must be remembered that as soon as a Signal is received for ManualReset EventWaitHandle, all threads waiting for the signal gets this notification and they resume their operation.



After signal has been generated, any thread which is waiting or will be waiting in future finds this open gate and just continue running unless the EventWaitHandle resets. In order to test this, lets click Open another window button three times showing three instances of AnotherWindow.



As we click the button “Signal another window”, the following code executes:
private void button2_Click(object sender, RoutedEventArgs e)
{
_waitHandleNamed.Set();
}

which is nothing but signaling the waiting threads on this event to resume operation (ManualReset). The threads in all the Window updates their respective Label contents by following code:
this.Dispatcher.BeginInvoke(new Action(() => this.textBlock1.Text = "Signal received"));

The windows are updates as follows:



Basically, the following statement creates a System level EventWaitHandle:
EventWaitHandle _waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, "MyWaitHandle");

We have to make sure that the name of this event is unique so that other applications and processes are not affected by these signals. Here we have defined a ManualRestEvent, we could also define an AutoReset EventWaitHandle. Then clicking button each time a different window would receive the signal and update the content of its Label. In order to prove the point of System level EventWaitHandle, let us create a new WPF project, WpfApplicationB_Signaling. This has just one window, MainWindow. The Window is defined as follows:

<Window x:Class="WpfApplicationB_Signaling.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock Height="39" HorizontalAlignment="Left" Margin="46,43,0,0"
Name="txtNotificationStatus" Text="Waiting For Signal!"
VerticalAlignment="Top" Width="368" />
</Grid>
</Window>

The code behind of the Window is as follows:

public partial class MainWindow : Window
{
EventWaitHandle _waitHandleNamed = new EventWaitHandle(false, EventResetMode.AutoReset,
"MyWaitHandle");

public MainWindow()
{
InitializeComponent();

ThreadPool.RegisterWaitForSingleObject(_waitHandleNamed, (o, e) =>
{
this.Dispatcher.BeginInvoke(new Action(() =>
this.txtNotificationStatus.Text = "Signal received"));
},
null, Timeout.Infinite, true);
}
}

Here we are using ThreadPool functionality of handling EventWaitHandle. We are registering EventWaitHandle using RegisterWaitForSingleObject method of ThreadPool. For this method, we need to specify which Event to wait on (_waitHandleNamed). We also specify if there is a Timeout. Since we can wait forever, we are specifying Timeout as Timeout.Infinite. The last argument is specified as true. This is to specify that we are interested in just one signal, otherwise, after finishing executing the handler, it would continue to wait for more notifications.

Now run this along with the previous WPF project. As you can see that we have opened three instances of AnotherWindow from 1st process. We also have MainWindow of second process opened:



Now click “Signal another window” button. All three AnotherWindow(s) and MainWindow from 2nd process updates as follows:



It is just like water flow. All taps which are opened, should get water from the flow:



Resume, only when all operations are completed!

In the above examples, we have considered the examples of AutoReset and ManualRest EventWaitHandles. .Net 4.0 has introduce a new signaling mechanism between threads. This is called CountdownEvent. Though this is named like the other two and it is also used in signaling between threads, it does not inherit EventWaitHandle unlike other two.

http://msdn.microsoft.com/en-us/library/system.threading.countdownevent.aspx

In this example, we can only notify the user when three operations complete. In order to keep the example simple, we are using three buttons. The click of each button would be considered as completion of an operation. When all three operation completes, the textblock should notify the user with text Process Finshed!!!. Just click each button only once :)



The definition of the above window is as follows:

<Window x:Class="WpfApplicationB_Signaling.WindowCountdownEventExample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WindowCountdownEventExample" Height="357" Width="669">
<Grid>
<Button Content="Execute Operation 1" Height="35" HorizontalAlignment="Left"
Margin="34,70,0,0" Name="btnOperation1" VerticalAlignment="Top" Width="185" Click="btnOperation1_Click" />
<Button Content="Execute Operation 2" Height="36" HorizontalAlignment="Left"
Margin="34,130,0,0" Name="btnOperation2" VerticalAlignment="Top" Width="185" Click="btnOperation2_Click" />
<Button Content="Execute Operation 3" Height="32" HorizontalAlignment="Left"
Margin="33,190,0,0" Name="btnOperation3" VerticalAlignment="Top" Width="188" Click="btnOperation3_Click" />
<TextBlock Height="33" HorizontalAlignment="Left" Margin="287,124,0,0"
Name="textNotificationProcessFinish" Text="Waiting for process completion..."
VerticalAlignment="Top" Width="283" />
</Grid>
</Window>

The code behind is as follows:

public partial class WindowCountdownEventExample : Window
{
CountdownEvent _waitCountDown = new CountdownEvent(3);

public WindowCountdownEventExample()
{
InitializeComponent();

new Thread(() =>
{
_waitCountDown.Wait();

this.Dispatcher.BeginInvoke(new Action(() => this.textNotificationProcessFinish.Text = "Process Finshed!!!"));
}
).Start();
}

private void btnOperation1_Click(object sender, RoutedEventArgs e)
{
_waitCountDown.Signal();
}

private void btnOperation2_Click(object sender, RoutedEventArgs e)
{
_waitCountDown.Signal();
}

private void btnOperation3_Click(object sender, RoutedEventArgs e)
{
_waitCountDown.Signal();
}
}

The above code is very simple. We have created an instance of CountdownEvent with the required signal count as 3. In the constructor, we have created a thread waiting for the CountdownEvent to finish. After each button click we are generating a signal. When the signal count reaches 3, the thread can resume. Now run the application and click each button only once. As soon as we click the third button, the window is updates as follows:



Zindabad!!!

Note: Since CountdownEvent does not inherit EventWaitHandle, there is no named CountdownEvent available in .net 4.0. Had there been any named event available for this type, we might implement many scenarios efficiently just by using CountdownEvent. This seems to be a big limitation.

Friday, December 17, 2010

WPF - Using Project Settings (Application / User Settings)

In this post, we will be discussing how we can use project properties in a WPF application. Specially, we will be considering how we can bind those properties to WPF elements.

Let us create a sample WPF application. We add a few settings to the project. In order to define settings, right click the startup project and select properties in Solution Explorer.


Now we define the settings. These settings might have different scopes. The available options are Application and User. An application properties is for all the user of the software. In case we updated a User setting, the update would just affect the current user.


It must be remembered that application wide settings are read-only. We can only change settings with user scope. In case we attempt to update the LabelText property defined above, it results in compile-time error.


Add a Window to the project. We add a few elements to the window as follows:

<Window x:Class="WpfApplication4.WindowBindingAppSettings"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ProjectProperties="clr-namespace:WpfApplication4.Properties"
xmlns:local="clr-namespace:WpfApplication4"
Title="WPF Project Settings Binding" Height="368" Width="616">
<Grid>
<Label Height="28" HorizontalAlignment="Left"
Margin="16,30,0,0" Name="label1" VerticalAlignment="Top"
Width="132" >
<Label.Content>
<Binding Source="{x:Static ProjectProperties:Settings.Default}" Path="LabelText" />
</Label.Content>
</Label>
<TextBox Height="27" HorizontalAlignment="Left" Margin="154,30,0,0"
Name="textBox1" VerticalAlignment="Top" Width="288" />
<TextBox Height="27" HorizontalAlignment="Left" Margin="154,63,0,0"
Name="textBox2" VerticalAlignment="Top" Width="287" >
<TextBox.Text>
<Binding Source="{x:Static ProjectProperties:Settings.Default}" Path="ManagerText"
Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
</TextBox>
<Label Height="27" HorizontalAlignment="Left"
Margin="447,63,0,0" Name="label2" VerticalAlignment="Top" Width="114" >
<Label.Content>
<Binding Source="{x:Static ProjectProperties:Settings.Default}" Path="ManagerText" />
</Label.Content>
</Label>
<Button Content="Update" Height="25" HorizontalAlignment="Left"
Margin="154,96,0,0" Name="button1" VerticalAlignment="Top" Width="135"
Click="button1_Click" />
</Grid>
</Window>

As you can see we have bound the Application setting LabelText to a Label label1. We also have a text box textBox1. We are binding the text of this TextBox to the user setting ManagerText. We are setting mode as TwoWay and copying the value to the actual setting as the user keep changing the text in the TextBox it is bound to. In order to prove that the setting is actually being updated, we are binding the same setting to another TextBlock. You will notice that as we keep typing in the TextBox, the TextBlock keeps itself updating. As the application keeps running, the application would be using the same value of the properties. If we want to persist it, we should be saving it. You can see that the button1_Click handler takes care of saving the settings.

The code behine is as follows:

public partial class WindowBindingAppSettings : Window
{
public WindowBindingAppSettings()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.Save();
}
}

WPF based development environment generally have a policy of no code-behind. Since Default is singleton, you can save it from anywhere from the application (including View Model). Now run the application, the application appears as follows (except the green boxes I drew in order to show you the bindng.


You can notice that the Label text is correctly updated with LabelText property. Now start typing in the second TextBox, you should notice that the same values keep appearing in the adjacent TextBlock. If we click "Update" button, the same values would appear when the application runs next time.

It would be a little different if we are developing application in VB.net. Instead of Binding through Project Properties, we need to bind it directly through MySettings.

<Window x:Class="WpfApplication4.WindowBindingAppSettings"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation";
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml";
xmlns:local="clr-namespace:WpfApplication1"
Title="WPF Project Settings Binding" Height="368" Width="616">
<Grid>
<Label Height="28" HorizontalAlignment="Left"
Margin="16,30,0,0" Name="label1" VerticalAlignment="Top"
Width="132" >
<Label.Content>
<Binding Source="{x:Static local:MySettings.Default}" Path="LabelText" />
</Label.Content>
</Label>
<TextBox Height="27" HorizontalAlignment="Left" Margin="154,30,0,0"
Name="textBox1" VerticalAlignment="Top" Width="288" />
<TextBox Height="27" HorizontalAlignment="Left" Margin="154,63,0,0"
Name="textBox2" VerticalAlignment="Top" Width="287" >
<TextBox.Text>
<Binding Source="{x:Static local:MySettings.Default}" Path="ManagerText"
Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
</TextBox>
<Label Height="27" HorizontalAlignment="Left"
Margin="447,63,0,0" Name="label2" VerticalAlignment="Top" Width="114" >
<Label.Content>
<Binding Source="{x:Static local:MySettings.Default}" Path="ManagerText" />
</Label.Content>
</Label>
<Button Content="Update" Height="25" HorizontalAlignment="Left"
Margin="154,96,0,0" Name="button1" VerticalAlignment="Top" Width="135"
Click="button1_Click" />
</Grid>
</Window>

The code behind in VB.net is as follows:

Public Class WindowBindingAppSettings
Private Sub button1_Click(ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs)

MySettings.Default.Save()
End Sub
End Class

Settings from Other Project:
Generally a solution file contains many projects. It is possible that one project needs to access the settings from other project. In order to do that we need to set the Access Modifier of the settings as Public. It is available from top right when you open Project's properties in Visual Studio. Let's assume we need to access settings from other Project OtherProject. The name of property is SettingProperty.
 OtherProject.Properties.Settings.Default.SettingProperty = "Some value"

WPF - DrawingContext and ShaderEffect

DrawingContext does not support ShaderEffect.

Using DrawingContext in OnRender() method of adorner, we can Push effect using PushEffect() method. But the strange thing is that DrawingContext.PushEffect() does not support ShaderEffect. All it supports is BitmapEffect :(. It seems to be a missing piece of functionality of conversion of all shaders to ShaderEffect.

So if you don't want to use BitmapEffect as it is obsolete now then DrawingContext wouldn't be of much use to you. There seems to be no other option though, e.g. we want to push effect to adorner, the only option available is to push BitmapEffect. Even PushEffect is decorated with ObsoleteAttribute in DrawingContext class.

http://msdn.microsoft.com/en-us/library/system.windows.media.drawingcontext.pusheffect.aspx

I have discussed about adorners here:

http://shujaatsiddiqi.blogspot.com/2010/07/wpf-adorners.html

If you want to study about ShaderEffect, you can refer this post:

http://shujaatsiddiqi.blogspot.com/2010/08/wpf-uielements-effects.html

Now you must be wondering why we are so much interested in having ShaderEffect with DrawingContext. The reason is the performance benefits with ShaderEffect compared to BitmapEffect. ShaderEffect uses pixel shaders in graphics processor (GPU). So it pushes the work outside the regular CPU. BitmapEffect provides a software solution to provide similar effects but it does not use new features of graphics processor.

Thursday, December 16, 2010

WPF - Porting applications to 64-bit (WOW64)

Many of the WPF projects are technology upgrade projects. After advent of WPF, everyone wants to get rid of old Win32 based display to cool WPF display with rich graphics. It is not just an upgrade of technology from Winform to Windows Presentation Foundation, but it is also upgrade in the underlying hardware architecture. New operating systems are 64-bit operating systems. While developing applications for these new operating system, we should be aware of the differences in the frameworks because of the architecture.

So desktop applications are going rich (using WPF) and they are being 64-bit. They will eventually be causing phase-out for 32-bit desktop applications. It also happens that these systems are not rolled off in a single shot. They are retired gracefully. I have even seen these systems co-exist for some duration before the old system is gotten rid of completely. So we have our 32-bit and 64-bit systems running on a 64-bit operating system.

Now the main question which might arise is, why should we go 64-bit. There are several benefits of developing 64-bit application. The maximum number for default thread pool thread increases from 1024 to 32768 in .net framework 4.0. 32-bit applications have a default address space limitation of 2 GB so going 64-bit increases the available address space for our applications.

When you look at Task Manager, you would find a few processes with *32 as part of their names. What is that?? Basically they are 32-bit processes running on 64-bit Windows. They are given special status in 64-bit OS and they are handled differently than their 64-bit counterparts.



How to develop 64-bit applications:
When we develop WPF applications, we can specify the intended platform for our application. Just take the properties of Startup project and go to Build tab. There are multiple options available for Platform Target. You can select the platform target of your choice. It can be 32-bit (x86), 64-bit (x64), Itanium or Any CPU (architecture-neutral). Here Any CPU is an interesting option. This is basically leaving the decision for run time. If the application is being run a 32-bit architecture, it would run as a 32-bit system, otherwise it would be running as per the architecture of the runtime. It is also possible that we have different target platform for Debug and Release configuration but that is rarely the case.



There has also been a little debate in the .net developer community about which option should be the default one. I would recommend reading this post discussing about why Any CPU should not be the default option. Currently, I find x86 as the default option for WPF application (.net 4.0) in VS2010 Ultimate.

http://blogs.msdn.com/b/rmbyers/archive/2009/06/08/anycpu-exes-are-usually-more-trouble-then-they-re-worth.aspx

Handling of 32-bit applications by 64-bit Windows Operating System:
Windows OS handles 32-bit applications with WOW technology. This is acronym for Windows-32 on Windows 64. This is basically a 32-bit OS emulator for 32-bit applications running on 64-bit Windows Operating System. Its main purpose is to create an artificial environment for 32-bit applications so that they could run on 64 bit Operating Systems without any changes. I have seen people using both WOW64 and WOW. I don’t know what is the official name. In this post, I have noticed myself using both. But wherever you see it, now you should know that I am referring to the same thing. . Basically WOW is the similar layer in 32-bit Operating Systems for 16-bit applications. So I would recommend using the term WOW64 in order to understand the desired architecture as 64-bit architecture.

http://en.wikipedia.org/wiki/Windows_on_Windows

http://msdn.microsoft.com/en-us/library/aa384249(v=VS.85).aspx



As is evident from the figure above, it is just a compatibility layer for 32-bit operating systems.

Mapping System32 folder to sysWow64 folder



If a 32-bit application requests access to the system32 folder, file system redirector redirects the request to sysWow64 folder instead. This folder contains the 32-bit versions of dlls. In case we want to bypass this direction, we should be usign %windir%\Sysnative instead.

Registry Redirection:
Wow maps all Registry operations to Wow6432Node. When a 32-bit app creates, updates or deletes a registry key, all of these operations are mapped to Wow6432Node by default by WOW. This redirection is performed by a special component of Wow64, called Registry Redirector. This copying of registry values is called Registry Relecton or Registry Mirroring.



This is a special pain-point when 32-bit and 64-bit application co-exist on the same machine. Both of these applications would be specifying same registry values to access the relevant registry keys. But since WOW maps the operations to Wow6432Node, the 64-bit application wouldn’t be able to find those registry keys. We have to specially specify Wow6432Node in registry path for 64-bit applications if we are planning to use same registry values for both. Later, when 32-bit application is phased off, we need to make sure that we have updated the path for these registry keys. We also need to make sure that we have tested the system thoroughly for this change. This is basically an observed behavior for one of our application. As a matter of fact, Windows is documented to be mapping /mirroring registry keys to Wow6432Node registry folder. In .net framework 4.0, this problem is specially addresses by providing special OpenSubKey support in RegistryKey class. Here we can specify if we want to get this value as a 32-bit application or 64-bit application. If we get it using 32-bit application, it would be using Wow64 in order to get the value, otherwise it would directly get the value of the registry key.

http://msdn.microsoft.com/en-us/library/microsoft.win32.registrykey.openbasekey.aspx

http://en.wikipedia.org/wiki/WoW64

HKEY_LOCAL_MACHINE\Software is mapped to HKEY_LOCAL_MACHINE\Software\Wow6432Node.

Program Files Directory:
A special program files directory is also created for 32-bit applications in the directory where OS is installed (Generally C:\). This is available as Program Files (x86).


IsWow64Process Function
We can also determine if an application is running under WOW64 technology using IsWow64Process function.
http://msdn.microsoft.com/en-us/library/ms684139(v=vs.85).aspx

Additional properties in Environment:
If we are building our application for a particular platform or Any CPU, we might still want to determine if the current process is a 64 bit process or not. There are two additions is Environment to determine:

Whether it is a 64-bit Operating System:
http://msdn.microsoft.com/en-us/library/system.environment.is64bitoperatingsystem.aspx

Whether it is a 64-bit process:
http://msdn.microsoft.com/en-us/library/system.environment.is64bitprocess.aspx

Saturday, December 11, 2010

WPF - ASynchronous Delegate Exception Model

In this post, we are going to discuss exception model of Asynchronous delegates. For those who have started development just starting with .net 4.0, they are old school for Task. Basically thread (including ThreadPool.QueueUserWorkItem based threads) are for providing "shoot and run" kind of flows. They don't us allow to return anything from them. If we needed to return a value, the only option we have is ASynchronous Delegate. It must be remembered that Asynchronous delegate would still be using ThreadPool thread so it will have all the benefits of using a ThreadPool thread.

Like BackgroundWorker, ASynchDelegate also has a special mechanism for dealing with exceptions raised during its operation. It is necessary to be aware of it. We will be discussing the use of ASynchDelegate in a sample WPF application. In this application, we will be taking input of two operands. The application would perform some complex calculation on these operands and display the result on the form. In order to keep the example simple, we would just sum these operands. We will not be verifying the inputs just for the same reason.


The XAML for the above display is as follows:

<Window x:Class="WpfApplication_ASynchDelegate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WindowASynchDelegate" Height="389" Width="595">
<Grid>
<TextBox Height="27" HorizontalAlignment="Left" Margin="138,22,0,0"
Name="textBoxOperand1" VerticalAlignment="Top" Width="311" />
<TextBox Height="27" HorizontalAlignment="Left" Margin="138,55,0,0"
Name="textBoxOperand2" VerticalAlignment="Top" Width="311" />
<TextBox Height="27" HorizontalAlignment="Left" Margin="138,143,0,0"
Name="textBoxResult" VerticalAlignment="Top" Width="311" />
<Button Content="Sum" Height="28" HorizontalAlignment="Left" Margin="139,88,0,0"
Name="button1" VerticalAlignment="Top" Width="143" Click="button1_Click" />
<Label Content="Operand 1" Height="27" HorizontalAlignment="Left" Margin="12,22,0,0"
Name="label1" VerticalAlignment="Top" Width="120" />
<Label Content="Operand 2" Height="27" HorizontalAlignment="Left" Margin="12,55,0,0"
Name="label2" VerticalAlignment="Top" Width="120" />
<Label Content="Result" Height="27" HorizontalAlignment="Left" Margin="12,143,0,0"
Name="label3" VerticalAlignment="Top" Width="120" />
</Grid>
</Window>

The code behind of the above window is as follows:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private decimal getSum(decimal operand1, decimal operand2)
{
decimal sum;
sum = operand1 + operand2;

return sum;
}

private void button1_Click(object sender, RoutedEventArgs e)
{
decimal operand1 = Decimal.Parse(this.textBoxOperand1.Text);
decimal operand2 = Decimal.Parse(this.textBoxOperand2.Text);

Func<decimal, decimal, decimal> getSumAsynchDelegate = getSum;

getSumAsynchDelegate.BeginInvoke(operand1, operand2,
(resultASynch) =>
{
var methodDelegate = (Func<decimal, decimal, decimal>)resultASynch.AsyncState;

this.Dispatcher.BeginInvoke(
new Action(() =>
this.textBoxResult.Text =
methodDelegate.EndInvoke(resultASynch).ToString()));
},
getSumAsynchDelegate);
}
}

In the Click event handler for the button, we have assigned the text entered in two input text boxes texBoxOperand1 and textBoxOperand2 to local variables operand1 and operand2. We have introduced an asynchronous delegate. This is expected to receive two decimal arguments and returns a decimal value. In the Asynchronous delegate declaration, the last value specified is the return type.

Func<decimal, decimal, decimal> getSumAsynchDelegate = getSum;

Although Asynchronous delegate seems to be similar to the Asynchronous methods (Asynchronous Programming Model - APM) because It has BeginInvoke and EndInvoke mechanism as in ASynchronous method and BeginInvoke returns IASynchResult as ASynchronous methods. But it must be remembered that BeginInvoke returns immediately after calling the method to the calling method. As discussed here, we can call BeginInvoke to invoke an Asynchronous delegate. It seems that we have provided four arguments to it. First two are for the method parameters [It depends on how many parameters you have for the method being called]. The third argument is the callback after the method finishes execution on a different thread. The last parameter is anything we want to pass. It is copied to ASynchState of the method. We can get this value in the callback. We have passed the delegate itself to ASynchState as we don't want to declare an instance member for it.

Now we discuss the lambda for the callback which gets called when asynchronous delegate finishes execution.

(resultASynch) =>
{
var methodDelegate = (Func<decimal, decimal, decimal>)resultASynch.AsyncState;

this.Dispatcher.BeginInvoke(
new Action(() =>
this.textBoxResult.Text =
methodDelegate.EndInvoke(resultASynch).ToString()));
},

As you can see, we have obtained the delegate from ASynchState property of resultASynch(IASynchResult). The interesting thing to notice is that we have used Dispatcher to copy value to textBoxResult.Text. This is because, unlike BackgroundWorker, the callback is not executed on UI thread. In order to get the returned value from the delegate, we need to call EndInvoke on the delegate passing IASynchResult as the argument. Since the method is expected to return a decimal value, we are converting it to string before assigning to the Text property of the text box.

Even if we don't call EndInvoke on ASynchronous Delegate, it still would finish execution. It wouldn't be making sense to use this delegate though in this kind of situation, as we are not expecting any returned value. But if we don't call EndInvoke then we lose any exception caused in the method called using asynchronous delegate. It is a silent exception. This is the same thing as we discussed in BackgroundWorker. We must be aware of all these silent failures in our application as it can lead our application to be in an unexpected state.

Let's update the method as follows:

[DebuggerNonUserCode]
private decimal getSum(decimal operand1, decimal operand2)
{
decimal sum;
sum = operand1 + operand2;

if (sum > 0)
throw new Exception("What did u do!");

return sum;
}

So if we don't call EndInvoke and update the definition of the method and don't call EndInvoke, the application would never know about the exception. If we don't use try / catch block with EndInvoke and the method results in an exception, the exception could end up in DispatcherUnhandledException if we are calling EndInvoke on a UIThread. Or AppDomain.CurrentDomain.UnhandledException if we are calling it in any other thread (as in the callback of asynchronous delegate).