Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Event based pattern to async CTP pattern

  _fbClient.GetCompleted += new EventHandler<FacebookApiEventArgs>(OnFetchPageNotification);
  _fbClient.GetAsync(_kNotificationPath, new Dictionary<string, object> { { "access_token", _kPageAccessToken } });

How to convert above code into awaitable code in wp7:

 object = await _fbClient.GetAsync(_kNotificationPath, new Dictionary<string, object> { { "access_token", _kPageAccessToken } });

I have CTP Installed and task parallel library also.

like image 467
Shashi Avatar asked Oct 12 '12 06:10

Shashi


1 Answers

The Async CTP came with a document that describes how to adapt each existing pattern to the Task Based Async pattern. It says that the Event based one is more variable, but does give one example:

public static Task<string> DownloadStringAsync(Uri url)
{
    var tcs = new TaskCompletionSource<string>();
    var wc = new WebClient();
    wc.DownloadStringCompleted += (s,e) =>
    {
        if (e.Error != null) tcs.TrySetException(e.Error);
        else if (e.Cancelled) tcs.TrySetCanceled();
        else tcs.TrySetResult(e.Result);
    };
    wc.DownloadStringAsync(url);
    return tcs.Task;
}

Where the original function that's being wrapped is DownloadStringAsync, the parameters match the parameters being passed to this function, and DownloadStringCompleted is the event that is being monitored.


(The same document appears to be downloadable here - the above sample (and more description) are from "Tasks and the Event-based Asynchronous Pattern (EAP)")

like image 79
Damien_The_Unbeliever Avatar answered Sep 20 '22 12:09

Damien_The_Unbeliever