Why would we want to call a WCF Service asynchronously?
The biggest reason to move from synchronous to asynchronous is performance. When a synchronous call is made, the current thread locks till the call is completed. It varies by OS and programming language but most application will have a set number of threads they can pull out of a thread pool. If to many threads are being utilized to retrieve data synchronously it could cause the entire application to lock up while it waits for a thread to become available. This is bad when end user usability plays a large part in development decisions today.
Asynchronous calls will call the WCF service and release the thread back into the thread pool. When the async call is completed a callback method is raised, this will pull out a new thread to consume the returning data.
In order to setup Async calls do the following:
- Right click on the service reference
- Select ‘configure service reference’
- Check ‘Allow generation of asynchronous operations’
- Ensure ‘Generate asynchronous operations’ is selected
- Click OK
Then to make the call in your code you just simple do this
C# version
private void AsyncTest() { WcfClient someWcfClient = new WcfClient(); //Setup a listener that can wait for the async call to complete someWcfClient.SimpleSearchCompleted += DocCallback; //call the async method and optionally pass in a parm someWcfClient.SimpleSearchAsync(someParm); } private void DocCallback(object sender, SinpleSearchEventArgs e) { // do something }
VB.NET version
Private Sub AsyncTest() Dim someWcfClient As New WcfClient() 'Setup a listener that can wait for the async call to complete AddHandler someWcfClient.SimpleSearchCompleted, AddressOf DocCallback 'call the async method and optionally pass in a parm someWcfClient.SimpleSearchAsync(someParm) End Sub Private Sub DocCallback(ByVal sender As Object, ByVal e As SinpleSearchEventArgs) ' do something End Sub