End method of asyn WCF service is never called

109 Views Asked by At

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.

1

There are 1 best solutions below

0
Jesse On BEST ANSWER

The problem was that the callback expects that the IAsyncResult in the case an instance of Task<string> to contain the state object that was passed into the BeginMethod, honestly this should have been obvious, but I was missing it. Different overloads of StarNew and ContinueWith did the trick. Posting my solution in order to save some head scratching for somebody.

IAsyncResult BeginMethod([params], AsyncCallback callback, object asyncState)
{
    var task = Task<MyReturnType>.Factory.StartNew((s)=>
    {
        //Do work here
        return value;
    }, state);

    return task.ContinueWith((t, s)=>
    {
        callback(t);
        return t.Result;
    });
} 

MyReturnType EndMethod(IAsyncResult asyncResult)
{
     return ((Task<MyReturnType>)asyncResult).Result;
}