There are multiple possibilities to call an Operation Asynchronous from a WCF Service:
Event Based Model
In this model, you register to a Completed
-Event and call your Operation with an Async
appended. The Callback Method is run on the same Thread that was used to call the Async Request, so you don’t need to invoke
it in case you’re modifying the UI.
Example:
public void AsyncCall() { MyServiceClient client = new MyServiceClient(); client.SomeMethodCompleted += SomeMethodCompletedCallback; client.SomeMethodAsync(<Your Parameters>); } public void SomeMethodCompletedCallback(object sender, SomeMethodCompletedEventArgs e) { MyServiceClient client = sender as MyServiceClient; if (client != null) { client.Close(); } <Your Return Value> = e.Result; }
IAsyncResult Model (Client-Side)
In this model, you call your Operation with a prepending Begin
. Note that the Callback is running on a Worker-Thread so if you’re modifying the UI, don’t forget to invoke
in the Callback.
Example:
public void AsyncCall() { MyServiceClient client = new MyServiceClient(); client.BeginSomeMethod(<Your Parameters>, new AsyncCallback(OnEndSomeMethod), client); } public void OnEndSomeMethod(IAsyncResult asyncResult) { MyServiceClient client = asyncResult.AsyncState as MyServiceClient; if (client != null) { <Your Return Value> = client.EndSomeMethod(asyncResult) client.Close(); } }
IAsyncResult Model (Server-Side)
This is the only “true” Asynchronous Model. It will run in a Server-Thread so you are able to get the status of a pending Operation or even cancel it. The implementation is more time-consuming than the other two but, in some cases, worth the effort.
I suggest you Google for some examples.
There is a very good series of posts at Dan Rigsby’s Blog
starting at this Post. Have a look at it to get more information and examples.