2017-06-02 131 views
1

如何從另一個線程訪問元素?在這種情況下,我在主線程(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」從 線程訪問不屬於一個在其中被創建。

+0

看吧:https://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c有一些(44我認爲)的在這裏回答。就我個人而言,我喜歡基於TAP的。 – Kevin

回答

1

你已經在做這個。您的Log方法顯示正確的操作 - 使用Invoke在UI線程上運行一些代碼。在這種情況下,你可以這樣做:

void Run() 
{ 
    var getLines = new Func<object>(() => richTextBox1.Lines); 
    var lines = (string[]) richTextBox1.Invoke(getLines); 
    foreach (var line in lines) 
    { 
     Log(line, label1); 
     Thread.Sleep(500); 
    } 
} 

但是,這確實沒有必要。看起來你真的想在單擊按鈕時只讀一次Lines屬性,並將它傳遞給後臺線程。

void Run(string[] lines) 
{ 
    foreach (var line in lines) 
    { 
     Log(line, label1); 
     Thread.Sleep(500); 
    } 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    var lines = richTextBox1.Lines; 
    var th = new ThreadStart(() => Run(lines)); 
    var th2 = new Thread(th); 
    th2.Start(); 
} 
+0

謝謝,效果很好! –

+0

@Johnred:請接受作爲回答。 –

0

這是另一個版本...不是說你不應該在用戶界面線程中運行的Log()方法中休眠!

private void button1_Click(object sender, EventArgs e) 
{ 
    ThreadStart th = new ThreadStart(() => Run()); 
    Thread th2 = new Thread(th); 
    th2.Start(); 
} 

void Run() 
{ 
    string[] lines = (string[])richTextBox1.Invoke(new Func<string[]>(() => richTextBox1.Lines)); 
    foreach (string line in lines) 
    { 
     Log(line, label1); 
     Thread.Sleep(500); 
    } 
} 

private void Log(string input, Label lbl) 
{ 
    lbl.Invoke(new Action(() => 
    { 
     lbl.Text = "Status: " + input; 
    })); 
}