Konrad
Konrad

Reputation: 135

Async implementation of synchronous WCF operation

I have .net 4.5 WCF service. I will rewrite the service implementation to use EF6 to access DB. This service has many clients and handle many calls. I cannot change service contract and clients. Does it make sense to use Async EF operations like SaveAsync, at the end my service must return T not Task (becouse of the old clients).

Update

Exaple operation contract

[OperationContract]
public object AddEntity(object entity)
{
    using(var context = new MyContext())
    {
        context.Add(entity)
        var task = context.SaveChangesAsync()

        return task.Result;
    }
}

So even I am usining async the thread will be block by task.Result. I cannot use await becouse than the operation contract must be changed to return Task. How to implement such scenario?

Upvotes: 4

Views: 803

Answers (2)

Guillaume
Guillaume

Reputation: 13128

[OperationContract]
public async Task<object> AddEntityAsync(object entity)
{
    using(var context = new MyContext())
    {
        context.Add(entity)
        return await context.SaveChangesAsync();
    }
}

WCF should detect the async method and will route calls properly with no modification required on client side.

I guess that SaveChangesAsync returns a Task and not a Task<object> but you know what to do ;)

Upvotes: 1

noseratio
noseratio

Reputation: 61656

Does it make sense to use Async EF operations like SaveAsync, at the end my service must return T not Task (becouse of the old clients).

Yes, it does make sense and will boost scalability of your WCF service. You don't have to change the contracts to take advantage of async APIs on the server side. The conversion can be totally transparent to the client, check this:

Different forms of the WCF service contract interface

Upvotes: 4

Related Questions