C# 的异步get 的三种方法

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace WebClientAsynProject
{
public class Program
{
#region HttpWebRequest异步GET

public static void AsyncGetWithWebRequest(string url)
{
var request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.BeginGetResponse(new AsyncCallback(ReadCallback), request);

}

private static void ReadCallback(IAsyncResult asynchronousResult)
{
var request = (HttpWebRequest)asynchronousResult.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var resultString = streamReader.ReadToEnd();
Console.WriteLine(resultString);
}
}

#endregion


#region WebClient异步GET

public static void AsyncGetWithWebClient(string url)
{
var webClient = new WebClient();

webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(url));
}

private static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//Console.WriteLine(e.Cancelled);
Console.WriteLine(e.Error != null ? "WebClient异步GET发生错误!" : e.Result);
}

#endregion


#region WebClient的OpenReadAsync测试

public static void TestGetWebResponseAsync(string url)
{
var webClient = new WebClient();
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(new Uri(url));
}

private static void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
var streamReader = new StreamReader(e.Result);
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
else
{
Console.WriteLine("执行WebClient的OpenReadAsync出错:" + e.Error);
}
}

#endregion

public static void Main(string[] args)
{
AsyncGetWithWebRequest("http://baidu.com");
Console.WriteLine("hello");

AsyncGetWithWebClient("http://baidu.com");
Console.WriteLine("world");

TestGetWebResponseAsync("http://baidu.com");
Console.WriteLine("jxqlovejava");

Console.Read();
}

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值