2017-05-06 88 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(); 
     }