程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#完成異步GET的辦法

C#完成異步GET的辦法

編輯:C#入門知識

C#完成異步GET的辦法。本站提示廣大學習愛好者:(C#完成異步GET的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成異步GET的辦法正文


本文實例講述了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://百度.com");
      Console.WriteLine("hello");
      AsyncGetWithWebClient("http://百度.com");
      Console.WriteLine("world");
      TestGetWebResponseAsync("http://百度.com");
      Console.WriteLine("jxqlovejava");
      Console.Read();
    }
  }
}

願望本文所述對年夜家的C#法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved