复制代码 代码如下:
public class AsyncExample
{
// Synchronous methods.
public int Method1(string param);
public void Method2(double param);
// Asynchronous methods.
public void Method1Async(string param);
public void Method1Async(string param, object userState);
public event Method1CompletedEventHandler Method1Completed;
public void Method2Async(double param);
public void Method2Async(double param, object userState);
public event Method2CompletedEventHandler Method2Completed;
public void CancelAsync(object userState);
public bool IsBusy { get; }
// Class implementation not shown.
}
复制代码 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace AsyncTest1.EAP
{
public class EAPRunTest1
{
public static void AsyncRun() {
Utility.Log("AsyncRun:start");
//测试网址
string url = "http://sports.163.com/nba/";
using (WebClient webClient = new WebClient()) {
//监控下载进度
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
//监控完成情况
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(url));
Utility.Log("AsyncRun:download_start");
}
}
static void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string log = "AsyncRun:download_completed";
log += "|cancel=" + e.Cancelled.ToString() ;
if (e.Error != null)
{
//出现异常,就记录异常
log += "|error=" + e.Error.Message;
}
else {
//没有出现异常,则记录结果
log += "|result_size=" + Utility.GetStrLen(e.Result);
}
Utility.Log(log);
}
static void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Utility.Log("AsyncRun:download_progress|percent=" + e.ProgressPercentage.ToString());
}
}
}
新闻热点
疑难解答
图片精选