将基于事件的模式转换为异步 CTP 模式 [英] Convert Event based pattern to async CTP pattern
问题描述
_fbClient.GetCompleted += new EventHandler(OnFetchPageNotification);_fbClient.GetAsync(_kNotificationPath, new Dictionary { { "access_token", _kPageAccessToken } });
如何在 wp7 中将上述代码转换为可等待代码:
object = await _fbClient.GetAsync(_kNotificationPath, new Dictionary { { "access_token", _kPageAccessToken } });
我也安装了 CTP 和任务并行库.
Async CTP 附带了一份文档,该文档描述了如何将每个现有模式调整为基于任务的异步模式.它说基于事件的更可变,但确实举了一个例子:
public static TaskDownloadStringAsync(Uri url){var tcs = new TaskCompletionSource();var wc = new WebClient();wc.DownloadStringCompleted += (s,e) =>{if (e.Error != null) tcs.TrySetException(e.Error);否则如果 (e.Cancelled) tcs.TrySetCanceled();否则 tcs.TrySetResult(e.Result);};wc.DownloadStringAsync(url);返回 tcs.Task;}
被包装的原始函数是 DownloadStringAsync
,参数与传递给该函数的参数匹配,DownloadStringCompleted
是被监控的事件.><小时>
(同一文档似乎可以在此处下载 - 以上示例(以及更多描述)来自任务和基于事件的异步模式 (EAP)")
_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.
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)")
这篇关于将基于事件的模式转换为异步 CTP 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!