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 testThreads
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void countToLots()
{
for (int i = 0; i < 10000000; i++)
{
textBox1.Text = "Counting to 10000000, value is " + i + Environment.NewLine;
}
}
public void countToZero()
{
for (int i = 10000000; i > 0; i--)
{
textBox2.Text = "Counting to 0, value is " + i + Environment.NewLine;
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread countUp = new Thread(new ThreadStart(countToLots));
Thread countDown = new Thread(new ThreadStart(countToZero));
countUp.Start();
countDown.Start();
}
private void button2_Click(object sender, EventArgs e)
{
textBox3.Text = "Bobby bob bob " + Environment.NewLine;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我真的需要尝试并掌握这一点 - 我只是不明白为什么我得到错误信息背后的理论.有人可以帮帮我吗?
跨线程操作无效:控制'textBox1'从其创建的线程以外的线程访问.
UI控件具有"线程亲和力"; 他们不希望被除了UI线程东西被触动; 包括阅读和写作属性..Text应该通过使用Invoke或者从UI线程完成赋值BackgroundWorker.
例如:
public void countToLots()
{
for (int i = 0; i < 10000000; i++)
{
// running on bg thread
textBox1.Invoke((MethodInvoker) delegate {
// running on UI thread
textBox1.Text = "Counting to 10000000, value is "
+ i + Environment.NewLine;
});
// running on bg thread again
}
}
Run Code Online (Sandbox Code Playgroud)
但请注意,这种类型的线程切换有开销.您不应该回调每次迭代 - 您应该(例如)每[n]次迭代更新UI - 在上面,例如每10000次.