您的位置:首页 > 其它

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

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

google_ad_client = "pub-6924533005275861";
google_ad_slot = "4211741364";
google_ad_width = 336;
google_ad_height = 280;




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]);


}


}





}





}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐