您现在的位置:首页 >> Asp.NET >> 内容

C#使用异步机制来取得一张网页

时间:2013-7-19 11:35:39 点击:

  核心提示:using System;using System.Net;using System.IO;using System.Text;using System.Threading;/// summary//...
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;


/// <summary>
///    使用异步机制的例子
/// </summary>
public class CAsync
{
const int MAX = 128;


    public static void  showUsage()
{
Console.WriteLine("使用异步机制来取得一张网页");
        Console.WriteLine();
        Console.WriteLine("Usage:");
        Console.WriteLine("GetURLAsync URL");
        Console.WriteLine("Examples:");
        Console.WriteLine("GetURLAsync http://www.microsoft.com");
}

private static void RespCallback(IAsyncResult ar)
    //private static void RespCallback(AsyncCallback ar)
    { 
HttpWebRequest req ;
        HttpWebResponse resp ;
        int BytesRead ;
        StreamReader Reader ;
        StringWriter Writer ;


        // 构建HttpWebRequest和HttpWebResponse实例
        req = ( HttpWebRequest)(Object)ar;
        resp = (HttpWebResponse)req.EndGetResponse(ar);


        BytesRead = 0;
        char[] Buffer=new char[MAX] ;


        // 实例化读、写流
        Reader = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8);
        Writer = new StringWriter();


        // 读写数据到缓冲区
        BytesRead = Reader.Read(Buffer, 0, MAX);
        while (BytesRead != 0 )
{
            Writer.Write(Buffer, 0, MAX);
            BytesRead = Reader.Read(Buffer, 0, MAX);
        }
        Console.WriteLine("Message = " + Writer.ToString());
    }



    public static int Main(string[] args)
    {
if (args.Length < 1)
{
showUsage();
            return 0;
}


Uri HttpSite ;
        HttpWebRequest wreq ;
        IAsyncResult r;
        HttpSite = new Uri(args[0]);
        wreq = (HttpWebRequest) WebRequest.Create(HttpSite);
        
        // 开始异步请求访问Internet资源
        r = (IAsyncResult) wreq.BeginGetResponse(new AsyncCallback(RespCallback), null);
        Thread.Sleep(30000);
        Console.WriteLine("Exiting.");
return 0;
    }
}

作者:不详 来源:网络
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
  • 青春网络编程技术(www.qcfupo.com) © 2020 版权所有 All Rights Reserved.
  • Powered by qcfupo! V3.0sp1
  • 百度友情链接: 百家乐[www.chinawestnews.net/aomenbaijiale/] 赌博网[www.chinawestnews.net/amdbwz/] 海立方[www.bjl.gov.cn/bjgylc/] 娱乐城[www.gtxrmzf.gov.cn/mapai/] 娱乐城[www.hfsf.gov.cn/yfgj/] 威尼斯人[www.hllinkou.gov.cn/baijile/] 澳门威尼斯[www.jjwgj.gov.cn/wnsr/] 888真人[www.lagm.gov.cn/888zhenren/] 百乐坊[www.laoling.gov.cn/blfylc/] 现金网[www.longyu.gov.cn/xjw/] 百家乐[www.chinawestnews.net/ambjl/] 新葡京娱乐场[www.sjzedu.gov.cn/jsylc/] 时时彩[www.snjw.gov.cn/ssc/] 赌博[www.chinawestnews.net/aomendubo/]