怎样用多线程在两个文本框里同时技术
我写了段代码,单个计数没问题,两个文本框同时计数页面卡死,好像线程阻塞一样,求解
- C# code
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); } }}
[解决办法]
this.Invoke(setTextDel,tb,i.ToString());
改为:this.BeginInvoke(setTextDel,tb,i.ToString());
[解决办法]
backgroudworker
[解决办法]
自己创建的线程不是UI线程, 而你打算在非UI线程访问UI, 这是不被允许的.你可以用
- C# code
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的更新就不会频繁到阻塞了。