用VS2012和Async,await 开发silverlight 5 程序
在silverlight上只能用异步编程,很操蛋!我感觉微软的决策人员吃错了药,使得开发难度增加很大。async和await难度更大,我经常碰到程序异常退出,但是try catch 也抓不到异常,只想骂微软他妈。
现在还没有实现async + WCF service 的例子,当然要用 async,await 和 Task based 异步操作WCF。哪位朋友要是实现了,如能给一个solution文档,请告知一下,谢谢!
不过基于老式的event-based倒是在silverlight 5上实现了async和await。
silverlight 和 WPF不一样限制特别多, WCF只能生成基于事件的异步编程,所以还无法直接使用 async和await,也无法生成Begin和end方法。
第一步要在VS2012 的project里安装 async targeting pack,否则会出现“Cannot find all types required by the ‘async’ modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?”等莫名其妙的语法错误。
第二步 添加web 或者 service reference,得到 Serviceclient
第三步给serviceClient 添加一个 task based extension 方法
[ServiceContract]
public interface IAsyncTest {
[OperationContract]
string Hello(string name);
}
using System.Threading.Tasks;
public static class extension {
public static Task<string> HelloAsync2(this AsyncTestClient client, string name) {
var tcs = new TaskCompletionSource<string>();
EventHandler<HelloCompletedEventArgs> handler = null;
handler = (s, e) => {
client.HelloCompleted -= handler;
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
client.HelloCompleted += handler;
try {
client.HelloAsync(name);
} catch {
client.HelloCompleted -= handler;
throw;
}
return tcs.Task;
}
}
第四步 在调用异步的方法加上async 关键字。
privateasync void Button_Click_1(object sender, RoutedEventArgs e) {
AsyncTestClient client = new AsyncTestClient();
string result = await client.HelloAsync2("my friend");
this.lblResult.Content = result;
}
看上去还是挺复杂的,当你有几个嵌套的异步 或者 循环 就值得使用上述async、await