How do I add async support to a .NET 4.5 WCF service so it doesn't break existing clients?

I have an existing WCF service with a SOAP endpoint using .NET 4.5. Most of the existing client code uses a ChannelFactory<T>

proxy approach .

I would like to change the service to support the model async

/ await

for various server and database side I / O.

The problem I am facing is that adding a keyword async

to WCF method calls requires changing their interface signatures to Task<T>

. This, in turn, seems to require a change in client code.

Keeping the async service code "all the way down", is there an easy way to keep the open API intact?

+3


source to share


1 answer


If you rename your server side method to include the word XxxxxAsync

, it won't change the client signature.

WCF automatically creates two endpoints for each method, a synchronous version and an asynchronous version. You can see this with WCF Test Client.

For example, the following service contract

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

public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }
}

      

When starting WCF Test Client, you will see 2 methods available

enter image description here



If I change the code to the following

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

public class Service1 : IService1
{
    public async Task<string> GetDataAsync(int value)
    {
        await Task.Delay(value);
        return string.Format("You entered and awaited: {0}", value);
    }
}

      

I can still call a synchronous method string GetData(int)

from my client

enter image description here

Please note, you will no longer be able to use the same clientide and serverside to represent the API (and in fact it shouldn't, the client-side interface must have both versions in it.Thus, the client can decide whether it wants to make a blocking call or not). However, you can still use shared models.

+6


source







All Articles