cantdoanything33
cantdoanything33

Reputation: 179

WCF asynchronous server side - proper implementation

I writing some WCF services and I want to write them in the most efficient way possible. That means that both server side and client side will expose async operations.

Client side

I am aware that on the client side contracts, I can expose async operations just by adding "Assync" suffix:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    string GetData(int value);

    [OperationContract]
    Task<string> GetDataAsync(int value);
}

Server side

The server side is not as obvious to me. On the server side I would like to keep only Async operations:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    Task<string> GetDataAsync(int value);
}

According to How to: Implement an Asynchronous Service Operation I should use IAssyncResult:

  [OperationContractAttribute(AsyncPattern=true)]
  IAsyncResult BeginServiceAsyncMethod(string msg, AsyncCallback callback, object asyncState);

This, however, seems tedious.

Why is the purpose of using IAssyncResult instead of Task-based async operations and what is the proper way of implementing async server side in WCF?

Upvotes: 2

Views: 718

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32058

If you look at the documentation (emphasis mine):

Asynchronous Programming Model (APM) pattern (also called the IAsyncResult pattern), where asynchronous operations require Begin and End methods (for example, BeginWrite and EndWrite for asynchronous write operations). This pattern is no longer recommended for new development. For more information, see Asynchronous Programming Model (APM).

versus

Task-based Asynchronous Pattern (TAP), which uses a single method to represent the initiation and completion of an asynchronous operation. TAP was introduced in the .NET Framework 4 and is the recommended approach to asynchronous programming in the .NET Framework. The async and await keywords in C# and the Async and Await operators in Visual Basic Language add language support for TAP. For more information, see Task-based Asynchronous Pattern (TAP).

So:

The article you are reading comes from the pre- .NET 4.0 era (so it is quite old). Use Tasks and forget that IAsyncResult exists.

Upvotes: 4

Related Questions