在Windows Phone中,HttpWebRequest和WebClient都是异步的,但网上很多文章说WebClient因为回调在UI线程,对性能会有点影响,目前我自己的app就是用WebClient实现,确实会影响UI线程,进度条也会卡。下面是一个使用HttpWebRequest异步下载的完整例子:
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.IO;
namespace WebRequest
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
delegate void DownDelegate(string content);
DownDelegate downDelegate;
//委托
public MainPage()
{
InitializeComponent();
}
private void setConent(string content)
{
textBlock1.Text = content;
}
private void ResponseCallback(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
WebResponse response = request.EndGetResponse(result);
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
string contents = reader.ReadToEnd();
Dispatcher.BeginInvoke(downDelegate, contents);//特别注意需要通过Dispatcher去更新UI进程
}
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
string url = "http://www.pocketdigi.com";
downDelegate = setConent;
System.Net.WebRequest request = HttpWebRequest.Create(url);
IAsyncResult result = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request);
//完成后调用委托,更新UI
}
}
}