C#實現(xiàn)異步GET的方法
更新時間:2015年07月11日 10:36:01 作者:優(yōu)雅先生
這篇文章主要介紹了C#實現(xiàn)異步GET的方法,涉及C#異步請求的相關(guān)實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#實現(xiàn)異步GET的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
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發(fā)生錯誤!" : 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("執(zhí)行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();
}
}
}
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
字符串陣列String[]轉(zhuǎn)換為整型陣列Int[]的實例
下面小編就為大家分享一篇字符串陣列String[]轉(zhuǎn)換為整型陣列Int[]的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12
C#開發(fā)微信門戶及應(yīng)用(1) 微信接口使用
這篇文章主要為大家詳細介紹了C#開發(fā)微信門戶及應(yīng)用第一篇,微信接口的使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
C#取得Web程序和非Web程序的根目錄的N種取法總結(jié)
C#取得Web程序和非Web程序的根目錄的N種取法,方便大家知道,有更好的方法,請說明2008-03-03

