Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF Service Client with .NET 4.5 Task-Based Async Operations, await never returns

I've added a WCF service reference to my .NET 4.5 app, using the default "Generate task-based operations" option under "Allow Generation of asynchronous operations." I'm calling the service from an async method of my own, sort of like so:

public async Task<SomeData> GetDataAsync()
{
    var client = new MyServiceClient();
    var result = await client.GetSomeDataAsync();

    return result;
}

The await client.GetSomeDataAsync() never completes (a breakpoint on the return statement never gets hit) and I don't get a time out or any other error, no exception is thrown, nothing. Fiddler shows that the client sent the request and the service responded almost instantly with the expected data, so the problem is on my side of the fence somehow.

If I switch to the synchronous version instead

var result = client.GetSomeData();

The call returns as expected.

What am I doing wrong?

like image 285
Mr. T Avatar asked Nov 30 '22 01:11

Mr. T


1 Answers

My chest hairs are tingling, Mr. T. I strongly suspect that further up your (client-side) call stack, you have some code that is calling Task<T>.Result or Task.Wait, which significantly increases the possibility of a deadlock (as I explain on my blog).

By default, when you await a Task, the await will capture a "context" and use that to resume the async method. If this is a context like a UI thread context, and then the code blocks the UI thread (i.e., calling Result or Wait), then the async method cannot resume on that UI thread.

I pity the fool who would attempt to mix synchronous and asynchronous code. Just use async all the way (as I describe in an MSDN article).

like image 177
Stephen Cleary Avatar answered Dec 04 '22 15:12

Stephen Cleary