直接代码:


页面
<Window x:Class="AsyncExampleWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0*"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button x:Name="startButton" Grid.ColumnSpan="2" Content="开始" HorizontalAlignment="Left" Margin="199,10,0,0" VerticalAlignment="Top" Width="75" Click="startButton_Click"/>
<TextBox x:Name="resultsTextBox" Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="250" Margin="10,36,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="500"/>

</Grid>
</Window>

后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Threading;
namespace AsyncExampleWPF
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}


private async void startButton_Click(object sender, RoutedEventArgs e)
{
resultsTextBox.Clear();
//SumPageSizes();
await SumPageSizesAsync();
resultsTextBox.Text += "\r\nControl returned to startButton_Click.";

}


class MyHttpClienHanlder : HttpClientHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Headers.Referrer = new Uri("http://www.google.com/");
request.Headers.Add("UserAgent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727)");
return base.SendAsync(request, cancellationToken);
}
}
private async Task SumPageSizesAsync()
{
MyHttpClienHanlder header=new MyHttpClienHanlder ();

var proxy = WebProxy.GetDefaultProxy();
proxy.Credentials = new NetworkCredential("XX", "XXXXX", "XXX");
header.Proxy = proxy;
HttpClient client = new HttpClient(header) { MaxResponseContentBufferSize = 1000000 };

// Make a list of web addresses.
List<string> urlList = SetUpURLList();

var total = 0;
foreach (var url in urlList)
{
// GetURLContents returns the contents of url as a byte array.
// byte[] urlContents = await GetURLContentsAsync(url);

byte[] urlContents = await client.GetByteArrayAsync(url);

DisplayResults(url, urlContents);

// Update the total.
total += urlContents.Length;
}

// Display the total count for all of the web addresses.
resultsTextBox.Text +=
string.Format("\r\n\r\nTotal bytes returned: {0}\r\n", total);
}


private List<string> SetUpURLList()
{
var urls = new List<string>
{
"http://msdn.microsoft.com/library/windows/apps/br211380.aspx",
"http://msdn.microsoft.com",
"http://msdn.microsoft.com/en-us/library/hh290136.aspx",
"http://msdn.microsoft.com/en-us/library/ee256749.aspx",
"http://msdn.microsoft.com/en-us/library/hh290138.aspx",
"http://msdn.microsoft.com/en-us/library/hh290140.aspx",
"http://msdn.microsoft.com/en-us/library/dd470362.aspx",
"http://msdn.microsoft.com/en-us/library/aa578028.aspx",
"http://msdn.microsoft.com/en-us/library/ms404677.aspx",
"http://msdn.microsoft.com/en-us/library/ff730837.aspx"
};
return urls;
}


private async Task<byte[]> GetURLContentsAsync(string url)
{
// The downloaded resource ends up in the variable named content.
var content = new MemoryStream();

// Initialize an HttpWebRequest for the current URL.
var webReq = (HttpWebRequest)WebRequest.Create(url);
var proxy= WebProxy.GetDefaultProxy();
proxy.Credentials=new NetworkCredential("jiangly", "@jly5228684", "ncs");
webReq.Proxy = proxy;


// Send the request to the Internet resource and wait for
// the response.
using (WebResponse response = await webReq.GetResponseAsync())
{
// Get the data stream that is associated with the specified URL.
using (Stream responseStream = response.GetResponseStream())
{
// Read the bytes in responseStream and copy them to content.
await responseStream.CopyToAsync(content);
}
}

// Return the result as a byte array.
return content.ToArray();
}


private void DisplayResults(string url, byte[] content)
{
// Display the length of each website. The string format
// is designed to be used with a monospaced font, such as
// Lucida Console or Global Monospace.
var bytes = content.Length;
// Strip off the "http://".
var displayURL = url.Replace("http://", "");
resultsTextBox.Text += string.Format("\n{0,-58} {1,8}", displayURL, bytes);
}
}
}

总结下为什么用异步, 在web下 本身就是多线程,为什么还要用异步呢?

1, 异步可以解决UI锁死, 这个可能大家都会遇到.

2, Net下的异步采用的是TPL 模式(传统异步是APM 模式), 可以大幅度提升性能.(来自于Dozer Zone的测试)

 

参考 http://blog.zhaojie.me/2010/10/pdc2010-the-future-of-csharp-and-vb-by-anders-hejlsberg-1.html  非常好的文章

 

 

posted on 2012-07-19 15:44  寂寞的DBOY  阅读(159)  评论(0编辑  收藏  举报