您的位置:首页 > 其它

事件异步(EAP)使用事件异步处理一些耗时操作

2016-07-11 23:44 519 查看
比如需要下载一些比较大的文件,如果使用会UI卡顿,使用异步可以节省一些时间

下面是一些例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo
{
class Program
{

static void Main(string[] args)
{
System.Net.WebClient client = new System.Net.WebClient();
client.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(client_DownloadStringCompleted);  //在异步资源下载操作完成时发生。
client.DownloadStringAsync(new Uri("https://www.baidu.com"));  //异步下载地址

for (int i = 0; i < 10;i++ )
{
Console.WriteLine("异步操作是执行此代码:"+i);
}

Console.ReadKey();
}

public static void client_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
{
System.Net.WebClient client = sender as System.Net.WebClient;
Console.WriteLine(e.Result);  //异步处理的结果
}

}
}


上述代码运行的结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: