Windows Phone开发 WebClient同步下载的实现(AutoResetEvent)

很多组件在Windows Phone中都缩水,比如WebClient类,只有异步下载功能,没同步下载功能.貌似Windows Phone中大多数跟网络相关的功能都默认异步,这样有个好处,比如在显示一张网络图片,不需要像Android中一样新开线程下载图片了,直接把Source设置成图片URL即可.但是没有同步下载功能,很多时候会很麻烦,比如说我们下载后要对数据进行处理,但是如果异步下载的话,下载好的数据只有在WebClient下载完调用的方法中才能得到,这样就需要把参数传递给下载完成的函数,比较麻烦.
同步下载原理:其实还是异步下载,只是使用了AutoResetEvent,让线程在开始下载的时候等待,下载完成事件里,通知原来的线程继续执行.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
        delegate void DownDelegate(string s);
        //定义委托,非UI线程需要与UI线程通讯,必须通过委托
        DownDelegate downDelegate;
        string html;
        public void CompletedDown(string s)
        {
            textBlock1.Text = s;
        }
        
        public MainPage()
        {
            InitializeComponent();
        }
        AutoResetEvent done = new AutoResetEvent(false);
        //AutoResetEvent可以让线程等待,直到收到通知
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            downDelegate = CompletedDown;
            Thread t = new Thread(new ThreadStart(ThreadProc));
            t.Start();  

        }
        public void ThreadProc()
        {
            WebClient webClient = new WebClient();
            webClient.DownloadStringCompleted+=new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            webClient.DownloadStringAsync(new Uri("http://www.pocketdigi.com"));
            done.WaitOne();
            //等待,收到通知后继续执行
            this.Dispatcher.BeginInvoke(downDelegate, html);
        }

        private void webClient_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
        {
            html = e.Result;
            done.Set();
            //通知线程继续执行
         }
 
    }
}

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记