• 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。编写代码如下:

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

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

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

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

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

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

        public MainPage() 
    {
    InitializeComponent();
    //调用普通异步
    SL4InitiateWebRequest();
    //并行任务库
    SL5InitiateWebRequest();
    }

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

  • 相关阅读:
    CF919F A Game With Numbers
    CF1005F Berland and the Shortest Paths
    CF915F Imbalance Value of a Tree
    CF1027F Session in BSU
    CF1029E Tree with Small Distances
    CF1037E Trips
    CF508E Arthur and Brackets
    CF1042F Leaf Sets
    [HNOI2012]永无乡
    [BZOJ1688][Usaco2005 Open]Disease Manangement 疾病管理
  • 原文地址:https://www.cnblogs.com/chengxingliang/p/2230319.html
Copyright © 2020-2023  润新知