Convert Event based pattern to async CTP pattern

2019-01-15 09:43发布

  _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.

1条回答
smile是对你的礼貌
2楼-- · 2019-01-15 10:13

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)")

查看更多
登录 后发表回答