I am trying to implement the asynchronous pattern in my WCF service. The BeginMethod is called, but the corresponding EndMethod is never called. Debugging the server, putting breakpoints in various places I noticed that callback that is passed to the BeginMethod never returns. I suspect that this is the reason why the EndMethod is never called.
Server code is structured as follows:
IAsyncResult BeginMethod([params], AsyncCallback callback, object asyncState)
{
var task = Task<MyReturnType>.Factory.StartNew(()=>
{
//Do work here
return value;
});
return task.ContinueWith(r=>
{
callback(task);
return r;
});
}
MyReturnType EndMethod(IAsyncResult asyncResult)
{
return ((Task<MyReturnType>)asyncResult).Result;
}
My breakpoint in EndMethod is never reached, and the line callback(task); never returns.
The problem was that the callback expects that the
IAsyncResultin the case an instance ofTask<string>to contain the state object that was passed into theBeginMethod, honestly this should have been obvious, but I was missing it. Different overloads ofStarNewandContinueWithdid the trick. Posting my solution in order to save some head scratching for somebody.