C# 跨线程操作UI元素
参考:http://www.cnblogs.com/zhangpengshou/archive/2008/04/28/1175289.html
http://blog.csdn.net/ghevinn/article/details/12065511
1. 使用MethodInvoker
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace InvokeTest
{
public partial class Form1 : Form
{
public static int x = 0;
public Form1()
{
InitializeComponent();
Thread thread = new Thread(new ThreadStart(ThreadProc));
thread.IsBackground = true;
thread.Start();
}
public void changeLable()
{
x++;
label1.Text = Convert.ToString(x);
}
public void ThreadProc()
{
MethodInvoker send = new MethodInvoker(changeLable);
while (true)
{
Thread.Sleep(1000);
BeginInvoke(send);
}
}
}
}
2. 使用EventHandler
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace InvokeTest
{
public partial class Form1 : Form
{
public static int x = 0;
public Form1()
{
InitializeComponent();
Thread thread = new Thread(new ThreadStart(ThreadProc));
thread.IsBackground = true;
thread.Start();
}
public void ThreadProc()
{
EventHandler send = new EventHandler(label1_Click);
while (true)
{
Thread.Sleep(1000);
BeginInvoke(send);
}
}
private void label1_Click(object sender, EventArgs e)
{
x++;
label1.Text = Convert.ToString(x);
}
}
}