多个线程中的操作无效

时间:2017-05-06 15:58:30

标签: c# multithreading asynchronous async-await

我需要两个并行执行的方法。 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"。如何解决这个问题?提前致谢。 附:由于无限循环,.NET 4.5的建议方法here不起作用。

2 个答案:

答案 0 :(得分:-1)

尝试从不同于UI线程的线程访问System.Windows.Forms.Control的成员将导致跨线程异常。

看看这个: How to update the GUI from another thread in C#?

答案 1 :(得分:-1)

用于交叉线程更改,您需要调用

使用此代码:

使用它只是为了元素在文本框,组合框,... 对于公共元素,您不需要这个

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

您的样本:

    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();
        }