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://baidu.com");
      Console.WriteLine("hello");
      AsyncGetWithWebClient("http://baidu.com");
      Console.WriteLine("world");
      TestGetWebResponseAsync("http://baidu.com");
      Console.WriteLine("jxqlovejava");
      Console.Read();
    }
  }
}

希望本文所述对大家的C#程序设计有所帮助。

(0)

相关推荐

  • C#实现异步发送邮件的方法

    本文实例讲述了C#实现异步发送邮件的方法.分享给大家供大家参考.具体如下: 下面的代码可以实现异步发送邮件,等邮件发送出去后会自动调用回调函数,这样在发送邮件时就不会卡住程序不动了 MailMessage m = new MailMessage ("item@jb51.net", "raja@jb51.net", "This is the subject for the authorized email.", "This is the

  • C#异步执行任务的方法

    本文实例讲述了C#异步执行任务的方法.分享给大家供大家参考.具体如下: // 异步执行耗时任务(适合不需要等它的执行结果的场景,如发邮件.发短信) Task.Factory.StartNew( () => { try { // 需要异步执行的操作比如发邮件.发短信等 SendEmail(...); } catch { //不做任何处理,防止线程异常导致程序崩溃 } } ); 希望本文所述对大家的C#程序设计有所帮助.

  • c#实现简单控制台udp异步通信程序示例

    实现客户端发送请求,服务器端响应机制 UDP客户端代码 复制代码 代码如下: using System;using System.Text;using System.Net;using System.Net.Sockets; namespace Client{    class Program    {        //客户端 Socket对象        private static Socket clientSocket;        //服务器端 终点        private

  • c#异步发送邮件的类

    首先要定义一个邮件信息的基类,如下所示: 复制代码 代码如下: /// <summary>/// Base message class used for emails/// </summary>public class Message{#region Constructor/// <summary>/// Constructor/// </summary>public Message(){}#endregion #region Properties/// &

  • C#实现异步连接Sql Server数据库的方法

    本文实例讲述了C#实现异步连接Sql Server数据库的方法.分享给大家供大家参考.具体分析如下: .net最新版提供了await方法,可以使我们可以很容易实现到数据库的异步连接 复制代码 代码如下: readonly string ConnectionString = "Data Source=database_server_name;Initial Catalog=Store;Integrated Security=True"; protected async void Exec

  • C#中异步回调函数用法实例

    本文实例讲述了C#中异步回调函数用法.分享给大家供大家参考.具体如下: static void Main(string[] args) { Func<string,string> showMessage = ShowMessage; //设置了回调函数Completed,不能有返回值 IAsyncResult result = showMessage.BeginInvoke("测试异步委托",new AsyncCallback(Completed),null); //半段异

  • C#异步调用实例小结

    本文实例讲述了C#异步调用的方法.分享给大家供大家参考.具体如下: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Threading; using System.Windows.Forms; namespace CW { public parti

  • C#基于UDP进行异步通信的方法

    本文实例讲述了C#基于UDP进行异步通信的方法.分享给大家供大家参考.具体如下: 服务器端: using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; namespace AsyncServer { public class UdpState { public UdpClient udp

  • C#异步绑定数据实现方法

    本文实例讲述了C#异步绑定数据实现方法.分享给大家供大家参考.具体如下: using System; using System.Collections.Generic; using System.Text; using System.Data.SqlClient; using System.Data; using System.Windows.Forms; namespace WindowsApplication2 { public class AsyncCallBackOpeartion {

  • C#异步委托调用实例分析

    本文实例讲述了C#异步委托调用实现方法.分享给大家供大家参考.具体如下: static void Main(string[] args) { //委托异步 Action<string> showMessage = ShowMessage; IAsyncResult result = showMessage.BeginInvoke("测试异步委托",null, null); //那在异步线程未完成工作以前主线程将处于阻塞状态 //等到异步线程结束,主线程才能继续工作 show

  • C#同步、异步远程下载文件实例

    1.使用HttpWebRequest/HttpWebResonse和WebClient 复制代码 代码如下: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); if (!response.ContentType.ToLower().St

随机推荐