谁给个源码 简洁 带注释。 关于多线程修改UI界面的。
委托代理多线程什么的。 弄很长时间了 就是不能彻底明白。 希望这次能够搞定。谢谢。
最简单最简单的。
一个form
一个button
点击 button 能够看着 button.text 在改变. 1-10000.
谢谢。
[解决办法]
应该比较简单的,用BackgroundWorker的例子
Safe, Even Simpler Multithreading in Windows Forms 2.0
http://www.mikedub.net/mikeDubSamples/SafeReallySimpleMultithreadingInWindowsForms20/SafeReallySimpleMultithreadingInWindowsForms20.htm
以及 ChrisSells用Invoke的三篇文章
http://msdn2.microsoft.com/en-us/library/ms993020.aspx
[解决办法]
- C# code
public partial class Form1 : Form{ private delegate void UIOperater(string str); Thread thrd; public Form1() { InitializeComponent(); } private void btnOK_Click(object sender, EventArgs e) { //打开一个线程 if (thrd == null || !thrd.IsAlive) { thrd = new Thread(new ThreadStart(ChangeBtnTxt)); thrd.Start(); } } private void ChangeBtnTxt() { uint i = 0; while (true) { i++; i = i % 10000; this.Invoke(new UIOperater(SetBtnTxt), new object[] { i.ToString() }); Thread.Sleep(100); } } private void SetBtnTxt(string str) { this.btnOK.Text = str; }}
[解决办法]
好像写错了一点,改过来
- C# code
//定义代理ShowStatus private delegate void ShowStatus(string str); ShowStatus showStatus = new ShowStatus(DoShowStatus);//用来更新界面元素的函数 private void DoShowStatus(string txt) { lock (this) { //sta_SysStatus是界面控件 sta_SysStatus.Text = txt; } }//调用 string str = "需要显示的文字"; this.BeginInvoke(showStatus, str);