C#实现异步GET的方法
程序员文章站
2023-11-20 22:10:46
本文实例讲述了c#实现异步get的方法。分享给大家供大家参考。具体实现方法如下:
using system;
using system.collections....
本文实例讲述了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(); } } }
希望本文所述对大家的c#程序设计有所帮助。