委托跨线程修改界面
工作线程中操作UI界面,禁止跨线程直接访问控件,使用委托和Invoke实现。
InvokeRequired:判断控件是否为调用线程创建
Invoke:同步调用方法
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace CrossThread
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public delegate void SetMsgDelegate(TextBox tb1, string msg);
public void SetMsg(TextBox tb1, string msg)
{
if (tb1.InvokeRequired)
{
SetMsgDelegate d1 = SetMsg;
tb1.Invoke(d1, tb1, msg);
}
else
tb1.Text = msg;
}
public void Plus()
{
//计算1+2+...+10
int sum=0;
for (int i = 1; i <= 10; i++)
sum += i;
SetMsg(textBox2, sum.ToString());
}
public void Fab()
{
//计算1*2*...*10
int sum = 1;
for (int i = 1; i <= 10; i++)
sum *= i;
SetMsg(textBox1, sum.ToString());
}
private void BtnCal_Click(object sender, EventArgs e)
{
Thread th1 = new Thread(new ThreadStart(Fab));
Thread th2 = new Thread(new ThreadStart(Plus));
th1.Start();
th2.Start();
}
}
}