解决vs2005"how to make cross-thread calls"超简单实例

在学习WebRequest Web Response对header操作时,涉及到异步操作,按实例运行出错,vs2005提示“how to make cross-thread calls...”,查了一下资料。将原来的代码
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]);
            }

        }

            
            
            
        }

    
}

posted on   公众号73只蚂蚁  阅读(469)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
历史上的今天:
2006-03-04 [导入]www.reactos.org一网友介绍的方向为“自己写操作系统的站点”

导航

< 2008年3月 >
24 25 26 27 28 29 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示