Async CTP 非常好用。 我看到了一些 Windows Phone 的例子,全部使用:
(程序集 AsyncCtpLibrary_Phone.dll,v2.0.50727,AsyncCtpExtensions)。
var client = new WebClient();
string data = await client.DownloadStringTaskAsync(new Uri(url));
或者类似上面的代码。
我如何为我的服务使用带有 async/await 的方法? (WCF)
今天所有的方法都是这样工作的:
service.MyRequestCompleted += service_myRequestCompleted;
service.MyRequestAsync();
我找不到为服务使用扩展方法的方法。
请您参考如下方法:
不幸的是,我还没有找到一个很好的方法来将此概括为任何事件,但很容易将其适应特定事件:
public static Task WhenRequestCompleted(MyService service) //can make it an extension method if you want.
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
service.MyRequestCompleted += () => //change parameter list to fit the event's delegate
{
tcs.SetResult(null);
};
service.MyRequestAsync();
return tcs.Task;
}
然后你可以这样做:
await WhenRequestCompleted(service);
//code that runs after the request is completed.
我假设您看到了此处的模式,因此您可以对其进行调整,以便它可以与其他类型的其他事件一起使用。
哦,如果事件有对你特别重要的参数,那么你可以让这个返回 Task<T>而不是 Task而不是使用 tcs.SetResult(null)您可以使用 lambda 的参数之一来设置结果。
