如题怎么跨线程给控件赋值
public partial class Form1 : Form
{
private Thread th1 = null;
private void btn_Start_Click(object sender, EventArgs e)
{
th1 = new Thread(StartSend);
Control.CheckForIllegalCrossThreadCalls = false;
th1.Start();
}
private void StartSend()
{
//这里给控件赋值会抛出异常
try{
tb_SendStates.Invoke(new SetTbText(TbValue), tb_SendStates, "没有数据要发送...");
}
catch()
{}
}
public delegate void SetTbText(TextBox tb, string text);
public void TbValue(TextBox tb,string text)
{
tb.Text = text;
}
private void Btn_Stop_Click(object sender, EventArgs e)
{
string b = th1.ThreadState.ToString();
if (th1.ThreadState.ToString() != "Running")
{
th1.Resume();
}
th1.Abort();
}
}
BeginInvoke
是将invoke改成BeginInvoke么?没效果啊.
方式1:Control.CheckForIllegalCrossThreadCalls = false;这句话放在构造函数中。然后别用Invork等调用,直接用单线程的方式写代码;
方式2:不需要Control.CheckForIllegalCrossThreadCalls = false,然后在代码块中,Invork~
这个刚试过了,不行啊 ...
@.F.: 你别吓我...
public MainForm() { InitializeComponent(); Test2(); } private void Test2() { int i = 0; //实例化线程 var th = new Thread(() => { while (true) { if (this.InvokeRequired) { //跨线程调用 this.Invoke(new Action(() => { this.Text = i.ToString(); })); } i++; Thread.Sleep(1000);//1s变化一次 } }); th.IsBackground = true;//设置为后台线程 th.Start();//启动线程 }
对,使用委托也可以