What is AsyncCallback and AsyncState for in Async WCF`?


What does the WCF framework do with the AsyncState and AsyncCallback in the following operation (service-side) implementation?

IAsyncResult BeginWork(<<Service call params>>, AsyncCallback callback, object state);

I am trying to understand

  1. Who are populating these?
  2. What are their purposes?
  3. Related to (2), what are the best practices in using these?

There are a couple of design patterns in .NET for exposing asynchronous methods.

This pattern with BeginX and EndX methods is called the Asynchronous Programming Model

In this pattern, you can always pass these two extra parameters:

1) AsyncCallback callback is a delegate which is called when the operation completes.

2) object state is any object you want to associate with the request.

The caller can provide these two parameters, or leave them null, depending on the use case.

See MSDN: Asynchronous Programming Model (APM)


In the case of an async WCF service implementation, WCF itself is the "client" and populates the two extra parameters.

Here's the workflow:

1) request comes from client.
2) WCF constructs an AsyncCallback and a state object
3) WCF calls your BeginX method and passes the parameters
4) In your method, you construct an IAsyncResult object using WCF's parameters
5) You initiate some background work and return your IAsyncResult object
6) WCF waits for its AsyncCallback to be called
7) WCF calls your EndX method and returns the response to the web service client.

The client doesn't know anything about this and may call this web service using either client-side synchronous or asynchronous calls.