When developing applications some time we have deal with the long running tasks.During the long running process its very import to to keep the UI responsive and feed updates to the user.When we comes to the service oriented architecture some times we have to deal with the long running services.Then UI does not hang while service works.To avoid such a behaviors we can use asynchronous pattern.
Basically WCF supports three type of Async patterns.
- The event-based asynchronous pattern .
- The IAsyncResult asynchronous pattern .
- The task-based asynchronous pattern.
This simple example is related to the event based async pattern.
first we need to implement the service.
1: public class LongRunner : ILongRunner
3: public string InitiateLongRunner()
5: // for the sake of the simplicity im just delaying the method execution.
7: return "Long running process has completed";
2: public interface ILongRunner
5: string InitiateLongRunner();
Please make sure your service up and running.
In this method we don’t need to add any additional coding to service implementation in order to support the asynchronous behavior.
Client proxy creation.
Add service reference.
Then go the advanced.
Then select “Generate asynchronous operation” radio button. (This will add async method to the service WSDL.)
Initiate the service call.
1: class Program
3: static void Main(string args)
5: using (MyClient.LongRunnerClient client = new MyClient.LongRunnerClient())
7: // register the event. this event fires when the service operation has completed.
8: client.InitiateLongRunnerCompleted += client_InitiateLongRunnerCompleted;
10: // call the long running operations
12: Console.WriteLine("Long runner has started.");
13: Console.WriteLine("Request is processing.");
18: /// <summary>
19: /// Handles the service reply.
20: /// </summary>
21: /// <param name="sender"></param>
22: /// <param name="e"></param>
23: private static void client_InitiateLongRunnerCompleted(object sender, MyClient.InitiateLongRunnerCompletedEventArgs e)
In Line 11 uses the async method than the original one . When we generate the WSDL including asynchronous methods, async method name came as original method name + “async” word.
result can be taken from the async method handler event args.(e.Result).