C# 实现线程内部与界面控件交互

线程内部无法直接调用web层控件的数据,及线程与界面数据无法直接调用,直接调用会报未知错误,一般解决方法有两种:

方法1:直接更改启动页面数据。是程序无法检测到线程,一般不建议这样解决:

方法二:使用委托。

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading; //引用命名空间
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public delegate void wdelegate(string str1); //创建委托

public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{

}
public void DoWork()//实现功能
{
wdelegate mi = new wdelegate(UpdateForm);
this.BeginInvoke(mi, new Object[] { "我是文本框" });
}

public void UpdateForm(string param1) //给文本框赋值的方法
{
this.TextBox1.Text = param1;
}

private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(DoWork)); //线程
thread.Start();//开始线程
}

}
}

 

posted @ 2016-03-04 17:33  相见欢空无言  阅读(456)  评论(0编辑  收藏  举报