Obi*_*007 2 asynchronous web-services task-parallel-library visual-studio-2012 windows-phone-8
到目前为止,似乎在VS2012中使用"生成基于任务的操作"导入服务引用是行不通的.它是灰色的.
使用WPF新项目的测试工作正常 - 我可以选择基于任务的操作或异步操作.
在任务中包装异步调用有一种简单的方法吗?
在任务中包装异步调用有一种简单的方法吗?
示例 WebClient.DownloadStringCompleted
public static class WebClientAsyncExtensions
{
public static Task<string> DownloadStringTask(this WebClient client, Uri address)
{
var tcs = new TaskCompletionSource<string>();
DownloadStringCompletedEventHandler handler = null;
handler = (sender, e) =>
{
client.DownloadStringCompleted -= handler;
if (e.Error != null)
{
tcs.SetException(e.Error);
}
else
{
tcs.SetResult(e.Result);
}
};
client.DownloadStringCompleted += handler;
client.DownloadStringAsync(address);
return tcs.Task;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
async void DownloadExample()
{
WebClient client = new WebClient();
await client.DownloadStringTask(new Uri("http://http://stackoverflow.com/questions/13266079/"));
}
Run Code Online (Sandbox Code Playgroud)