解决 vs2005编译错误提示 "how to make cross-thread calls"超简单实例

这两天在学习WebRequest Web Response对header操作时,涉及到异步操作,按实例运行出错,vs2005提示“how to make cross-thread calls...”,查了一下资料。将原来的代码

<script type="text/javascript"> google_ad_client = "pub-6924533005275861"; google_ad_slot = "4211741364"; google_ad_width = 336; google_ad_height = 280; </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>

 

using  System;
using  System.IO;
using  System.Collections.Generic;
using  System.ComponentModel;
using  System.Data;
using  System.Drawing;
using  System.Text;
using  System.Windows.Forms;
using  System.Net;

namespace  Accessing_the_internet
{
    
public partial class Form1 : Form
    
{
        
public Form1()
        
{
            InitializeComponent();

            WebRequest wrq 
= WebRequest.Create("http://www.123de6.cn");
            wrq.BeginGetResponse(
new AsyncCallback(OnResponse), wrq);
        }

        
protected void OnResponse(IAsyncResult ar)
        
{
            WebRequest wrq
=(WebRequest)ar.AsyncState;
            WebResponse wrs
=wrq.EndGetResponse(ar);
            
            
//read the response
            WebHeaderCollection whc = wrs.Headers;
            MethodInvoker mi
=new MethodInvoker()
            
            
for (int i = 0; i < whc.Count; i++)
            
{
                listBox1.Items.Add(
"Header"+ whc.GetKey(i)+" : " +whc[i]);
            }

        }




    }


}



改为这样,就可以实现对主线程listbox的操作。

 

using  System;
using  System.IO;
using  System.Collections.Generic;
using  System.ComponentModel;
using  System.Data;
using  System.Drawing;
using  System.Text;
using  System.Windows.Forms;
using  System.Net;

namespace  Accessing_the_internet
{
    
public partial class Form1 : Form
    
{
        WebHeaderCollection whc;
        
public Form1()
        
{
            InitializeComponent();

            WebRequest wrq 
= WebRequest.Create("http://www.123de6.cn");
            wrq.BeginGetResponse(
new AsyncCallback(OnResponse), wrq);
        }

        
protected void OnResponse(IAsyncResult ar)
        
{
            WebRequest wrq
=(WebRequest)ar.AsyncState;
            WebResponse wrs
=wrq.EndGetResponse(ar);
            
            
//read the response
            whc = wrs.Headers;
            MethodInvoker mi 
= new MethodInvoker(controla);
            
this.BeginInvoke(mi);
            
            
        }

        
private void controla()
        
{
            
for (int i = 0; i < whc.Count; i++)
            
{

                listBox1.Items.Add(
"Header" + whc.GetKey(i) + " : " + whc[i]);
            }

        }

           
     }

    
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值