Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF 3.5, AsyncBridge. Wrap in async-await

At work I'm currently stuck in 3.5, but we are using the asyncbridge for async-await. We're using alot of old WCF async calls, and I want to wrap this into the new async-await pattern.

I'm wrapping this as follows:

    // async is wrong
    public /*async*/ Task<ScannedDocumentResult> GetScannedDocumentsTask(String assignmentId)
    {
        TaskCompletionSource<ScannedDocumentResult> tcs = new TaskCompletionSource<ScannedDocumentResult>();
        EventHandler<GetScannedDocumentsCompletedEventArgs> handler = null;
        handler = (o, e) =>
            {
                if (e.UserState != tcs)
                    return;

                if (e.Error != null)
                    tcs.SetException(e.Error);
                else if (e.Cancelled)
                    tcs.SetCanceled();
                else
                    tcs.SetResult(e.Result);

                GetScannedDocumentsCompleted -= handler;
            };
        GetScannedDocumentsCompleted += handler;
        GetScannedDocumentsAsync(assignmentId, tcs);

        return tcs.Task;            
    }

The following are genereted in the 3.5 WCF proxy:

GetScannedDocumentsAsync GetScannedDocumentsCompleted GetScannedDocumentsEventArgs

Something tells me that this can be done alot cleaner, have I missed something cruical?

Also, will this method execute async at all? Compiling with the async operator just generates an error.

like image 958
Stígandr Avatar asked Aug 21 '13 06:08

Stígandr


1 Answers

You should also be getting a BeginGetScannedDocuments and EndGetScannedDocuments, which you can wrap using TaskFactory.FromAsync. I have a blog post that shows how to use task wrappers with old-school (pre-4.5) WCF (both on the server and client).

like image 68
Stephen Cleary Avatar answered Oct 14 '22 11:10

Stephen Cleary