2017-05-06 86 views
0

我需要兩種方法並行執行。 Work()更改無限循環內的數據。 Represent也將更改後的數據放入無限循環內的TextBox多線程中的無效操作

Log log = Log.GetInstance; //singleton 
private void Work() 
     { 
      while (true) { //changing log } 
     } 

private async void Represent() 
     { 
      await Task.Run(() => 
      { 
       while (true)  
       { 
        String str = String.Empty; 
        //generating str from log 
        textBox.Text = str; 
       } 
      }); 
     } 

private async void button_Click(object sender, EventArgs e) 
     { 
      await Task.Run(() => Work()); 
     } 
public MainForm() 
     { 
      Represent(); 
     } 

的問題是,textBox.Text = str;生成錯誤"invalid operation in multiple threads: attempt to access the control "textBox" from a thread in which it was created"。如何解決這個問題?提前致謝。 P.S.由於無限循環,.NET 4.5的建議方法here不起作用。

+0

希望這個錯誤信息不是字面上的意思 – harold

回答

-1

跨調線,你需要調用

使用此代碼:

使用這只是用於元素是像文本框,組合框的UI, ..... 公共元素你不需要這個

this.Invoke(new Action(() => { /*your code*/ })); 

爲你的採樣le:

Log log = Log.GetInstance; //singleton 
private void Work() 
     { 
      while (true) { //changing log } 
     } 

private async void Represent() 
     { 
      await Task.Run(() => 
      { 
       while (true)  
       { 
        String str = String.Empty; 
        //generating str from log 
        this.Invoke(new Action(() => { textBox.Text = str;})); 
       } 
      }); 
     } 

private async void button_Click(object sender, EventArgs e) 
     { 
      await Task.Run(() => Work()); 
     } 
public MainForm() 
     { 
      Represent(); 
     }