如何從另一個線程訪問元素?在這種情況下,我在主線程(GUI)中有一個richtextbox,我在輔助線程上運行一個方法。我想通過輔助線程訪問richeditbox示C#從其他線程訪問元素
private void Log(string input, Label lbl)
{
lbl.Invoke(new Action(()=>
{
lbl.Text = "Status: " + input;
Thread.Sleep(50);
}));
}
void Run()
{
foreach (string line in richTextBox1.Lines)
{
Log(line, label1);
Thread.Sleep(500);
}
}
private void button1_Click(object sender, EventArgs e)
{
ThreadStart th = new ThreadStart(() => Run());
Thread th2 = new Thread(th);
th2.Start();
//th2.Join();
}
以下錯誤:
無效的線程操作:控制「richTextBox1」從 線程訪問不屬於一個在其中被創建。
看吧:https://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c有一些(44我認爲)的在這裏回答。就我個人而言,我喜歡基於TAP的。 – Kevin