Before implementing our asynchronous pattern in WCF, I think
it is better to give an introduction to asynchronous pattern and its
applications in this section. Many of you may be partially or completely
familiar with this design pattern so you can escape this section and read the next
For long running executions in an application, there is a probability
that a current thread cannot keep executing because it may stop user
interface. For example, when a Windows application goes to a new state to
execute a long running process, windows may freeze and even crash. One
solution is to move this execution to another thread and let it follow there.
Asynchronous pattern comes into play to solve this issue and
Microsoft has a built-in mechanism for this pattern in its great .NET
Framework. Microsoft's implementation of this pattern consists of these pieces:
Two methods for an asynchronous operation
An object which implements IAsyncCallback
A callback delegate
This way, execution of a method splits into two steps. In
the first step you create the background process and start it and in the second
step you listen for changes in process and wait until it finishes.
For example, if we have a method to add two numbers and name
it Add() then asynchronous version of this method
consists of two methods: BeginAdd() and EndAdd().
If Add() has a signature like
Then BeginAdd() has this
IAsyncResult BegingAdd(int x, int y, AsyncCallback callback, object state);
As you see, BeginAdd() has two
extra parameters in comparison with original Add()
AsyncCallback: A delegate that gets an IAsyncResult
parameter and does not return anything. It will be called when asynchronous
operation is completed.
object: It keeps the state of the asynchronous operation as an IAsyncResult object.
This method also returns an IAsyncResult
object rather than the original integer type.
On the other hand, EndAdd() has the
int EndAdd(IAsyncResult ar);
As you see, this method only has one parameter of IAsyncResult type. This object gives all necessary
information about the state of operation and has the following properties.
AsynState: Gets an object that provides some information about
AsycWaitHandler: Gets a WaitHandle to
wait for an asynchronous operation to complete.
CompletedSynchronously: Indicates if the asynchronous operation
has completed synchronously.
IsCompleted: Indicates if the asynchronous operation has
Having this background information, we can step into WCF and
talk about asynchronous pattern implementation in it which may be a little
different than what you have seen in other parts of .NET Framework.