异步方式访问网页

采用BackgroundWorker,在后台执行程序,往往比开新线程更简单和更加安全。

简单的使用方法

System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker();
//定义需要在子线程中干的事情

bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoWork);
//定义执行完毕后需要做的事情

bw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
//开始执行 bw.RunWorkerAsync();
static void bw_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
  MessageBox.Show("Complete"+Thread.CurrentThread.ManagedThreadId.ToString());
}
static void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
  MessageBox.Show(Thread.CurrentThread.ManagedThreadId);
}

我改写了一个通知页面处理的方法,不需要结果,通知了主程序就继续前进,保证效率

/// <summary>
/// 访问网页(异步方式),只需激活网页,不要结果
/// </summary>
/// <param name="url">网页地址</param>
/// <returns></returns>
public static void Notify(string url)
{
    BackgroundWorker bw = new BackgroundWorker();  //定义一个背景对象

    //定义需要在子线程中干的事情
    bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoWork);
    bw.RunWorkerAsync(url);

}

/// <summary>
/// 后台执行:打开网页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    string url = (string)e.Argument;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    string content = "";
    try
    {              
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();               
        if (response.StatusCode == HttpStatusCode.OK) //防止无响应
        {
            StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312"));
            content = reader.ReadToEnd();
            reader.Close();
        }
        log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType).Debug("异步方式打开网页:" + url+",返回长度:"+content.Length.ToString());
    }
    catch (Exception ex)
    {
        log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType).Error("[Notify]打开网页" + url + "出错:" + ex.Message);
    }
}

执行效果不错,这是跟踪的情况:

image

可以看到,假如同时发生多个访问的话,系统会分配不同的线程执行(前面的是线程号)。

posted @ 2010-07-24 22:14  jetz  阅读(543)  评论(0编辑  收藏  举报