C# 多线程操作同一个textbox
- C# code
private object sync = new object(); delegate void SetTextCallback(string text); private void WorkThread() { this.ReadText(); this.WorkThread();//为了循环 } private void ReadText() { int a; lock(sync) { a = Convert.ToInt32(textBox1.Text); } Thread.Sleep(1000); a++; lock(sync) { this.SetText(a.ToString()); } } private void SetText(string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } }
这样一段代码用下面代码创建线程
- C# code
Thread t = new Thread(new ThreadStart(WorkThread)); t.Start();
循环指向那段启动代码启动的貌似也只是一个线程.
怎样才能用一个多个线程公用一个 方法? 或者我的代码就不对?
[解决办法]
使用线程数组
Thread t[i]=new Thread(new ThreadStart(WorkThread));
t[i].Start();