日期:2014-05-18 浏览次数:20992 次
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace ParaThread { public partial class Form1 : Form { public Form1() { InitializeComponent(); setTextDel = new SetTextBoxTextDelegate(this.SetText); } delegate void SetTextBoxTextDelegate(TextBox textbox,string text); SetTextBoxTextDelegate setTextDel = null; private void SetText(TextBox textbox, string text) { textbox.Text = text; } private void btnCountA_Click(object sender, EventArgs e) { ParameterizedThreadStart ptsA = new ParameterizedThreadStart(this.process); Thread thA = new Thread(ptsA); thA.IsBackground = true; thA.Start(txtNumA); } private void process(object textBox) { TextBox tb = (TextBox)textBox; for (int i = 0; i < 9999999; i++) { this.Invoke(setTextDel,tb,i.ToString()); //Thread.Sleep(100);加上Sleep,两个文本框能同时计数 } } private void btnNumB_Click(object sender, EventArgs e) { ParameterizedThreadStart ptsB = new ParameterizedThreadStart(this.process); Thread thB= new Thread(ptsB); thB.IsBackground = true; thB.Start(txtNumB); } } }
WindowsFormsSynchronizationContext Sync = new WindowsFormsSynchronizationContext(); private void SetText(TextBox textbox, string text) { Sync.Send(_=> { textbox.Text = text; },null); }
------解决方案--------------------
你每次执行process方法的时候,每次循环都会更新一次UI,UI线程都会this.BeginInvoke(...)中...处的代码占用,而一次循环的操作间隔太短,因此阻塞是不可避免的。
你可以通过Thread.Sleep(1);来让当前循环休眠一下,这样UI就不会被阻塞了。
总之就是你process里面一次循环的间隔时间稍微长一点的话,UI的更新就不会频繁到阻塞了。