为了增强用户体验 我在一个winform项目中用到了多线程
但是 不是很熟悉多线程 此前我一直做web开发的
请大家看 private void button2_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(this.OutputThread));
t.IsBackground = true;
t.Start();
} private void OutputThread()
{
//此处引用界面上的Control回报错 说不能跨线程访问这些东西
// 但是我这里需要用到很多Control 甚至是控制它们显示的值等等, 我该怎么办?
}
但是 不是很熟悉多线程 此前我一直做web开发的
请大家看 private void button2_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(this.OutputThread));
t.IsBackground = true;
t.Start();
} private void OutputThread()
{
//此处引用界面上的Control回报错 说不能跨线程访问这些东西
// 但是我这里需要用到很多Control 甚至是控制它们显示的值等等, 我该怎么办?
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;namespace WindowsApplication13
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private delegate void MoveLabel(int val);//声明代理
Thread td;
private void Form1_Load(object sender, EventArgs e)
{
td = new Thread(new ThreadStart(ThreadFun));
td.Start();
}
void SetOffset(int val)
{
label1.Text = "从子线程里传入的值是:" + val.ToString();
}
private void ThreadFun()
{
if (this.InvokeRequired)
{
MoveLabel d = new MoveLabel(SetOffset);
object[] arg = new object[] { 1 };//要传入的参数值
this.Invoke(d, arg);
}
}
}
}demo 下载:http://download.csdn.net/source/1584578