Silverlight 5 RC新特性探索系列:13.Silverlight 5 RC 新增对并行任务库(TPL)的支持

简介:

      在Silverlight 5 RC版本中新增了对并行任务库(Task Parallel Library)的支持,Task Parallel Library简称TPL,它是指一个或者多个任务同时运行,类似线程或者线程池。在本例中将会以并行任务库和异步获取数据进行对比。相关资料可以看http://msdn.microsoft.com/en-us/library/dd537609.aspxhttp://www.cnblogs.com/vwxyzh/tag/TPL/

        首先新建一个Silverlight 5项目,在其Web项目中添加一个新的xml文件helloWorld.xml。编写代码如下:

 

 
  1. <?xml version="1.0" encoding="utf-8" ?> 
  2. <a>111</a> 

        然后我们看Silverlight 4及之前的版本中如何异步获取数据,其代码如下:

 

 
  1. //SL4异步获取结果 
  2. private void SL4InitiateWebRequest() 
  3.     HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:12887/helloWorld.xml"); 
  4.     request.BeginGetResponse(new AsyncCallback(onRequestComplete), request);  
  5. private  void onRequestComplete(IAsyncResult asynchronousResult) 
  6.     HttpWebRequest request = asynchronousResult.AsyncState as HttpWebRequest; 
  7.     HttpWebResponse response = request.EndGetResponse(asynchronousResult) as HttpWebResponse; 
  8.     var s = response.GetResponseStream(); 
  9.     var reader = new StreamReader(s); 
  10.     string xmlFileText = reader.ReadToEnd(); 
  11.     this.Dispatcher.BeginInvoke(() => { MessageBox.Show("这是SL4获取Xml数据:"+xmlFileText); }); 

        然后我们再看通过TPL来异步获取数据,当然这之前需要using System.Threading.Tasks。

 

 
  1. //silverlight 5并行计算 
  2.  private void SL5InitiateWebRequest() 
  3.  { 
  4.      string uri = "http://localhost:12887/helloWorld.xml"
  5.      var request = HttpWebRequest.Create(uri);  
  6.      var webTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, 
  7.          request.EndGetResponse,TaskCreationOptions.None) 
  8.          .ContinueWith(task =>  
  9.          {  
  10.              var response = (HttpWebResponse)task.Result;  
  11.              var stream = response.GetResponseStream(); 
  12.              var reader = new StreamReader(stream);  
  13.              string xmlFileText = reader.ReadToEnd(); 
  14.              this.Dispatcher.BeginInvoke(() => { MessageBox.Show("这是SL5获取Xml的数据:" + xmlFileText); }); 
  15.              }); 
  16.  }  

        最后我们客户端调用上面的两种方式来获取数据。

 

 
  1. public MainPage()  
  2.     InitializeComponent(); 
  3.     //调用普通异步 
  4.     SL4InitiateWebRequest(); 
  5.     //并行任务库 
  6.     SL5InitiateWebRequest(); 
  7. }  

        运行效果一致,如下两图,另外如需源码请点击SL5Ansyc.zip 下载。


本文转自程兴亮 51CTO博客,原文链接:http://blog.51cto.com/chengxingliang/827058


相关文章
|
前端开发 Java C#
使用 XAML 替代 HTML,新版 Microsoft Store 性能显著提升
使用 XAML 替代 HTML,新版 Microsoft Store 性能显著提升
156 0
|
安全 API 开发工具