Search code examples
c#.netwcfasynchronous

How to properly change WCF web service method from synchronous to async


I'm working on a .Net framework application that exposes web service to various clients using WCF. The application currently performs all data access synchronously, and I'm needing to modify those repositories to async/await database calls. I've made the modifications to a couple of data access methods so far, and modified the calling methods to async up the chain to the actual web service methods themselves. This required changing the ServiceContract interface on the server, since these methods now return a "Task" instead of the base data type that they did before.

So, for example, on the server side of things, the Interface changes from:

[ServiceContract]
public interface IMyContract
{
    [OperationContract()]
    string MyMethod1();

    [OperationContract()]
    Boolean MyMethod2();
}

to:

[ServiceContract]
public interface IMyContract
{
    [OperationContract()]
    Task<string> MyMethod1();

    [OperationContract()]
    Task<Boolean> MyMethod2();
}

The original contract interface on the client side of things remains unchanged. So, the client makes a call to web service method MyMethod1 expecting a string as a return value, but the server actually returns Task<string>.

This seems to work ok in my testing, but just wondering if this is the correct way to set it up. Are there any config settings, method attributes, etc. that should be applied anywhere, or an alternative better way to handle this? It makes sense to me that the client shouldn't need to have any knowledge of the implementation details of the web service methods (synchronous vs async in this case), but want to make sure this setup is workable, since the return type of the methods specified in the contract no longer match between server and client as they did before. The clients aren't changing to make an async call to the web services. It's just the implementation of the web service methods themselves that is being changed to async.

Thanks in advance for any replies.


Solution

  • Your operation is normal. The task-based asynchronous pattern is the preferred way to implement asynchronous operations.You just need the follow-up implementation method like this:

    public class MyContract:IMyContract
    {
       // ...  
       public async Task<string> MyMethod1(string msg)
       {
          return Task<string>.Factory.StartNew(() =>
          {
             return msg;
          });
       }  
       // ...  
    }