Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/260.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 多线程中的操作无效_C#_Multithreading_Asynchronous_Async Await - Fatal编程技术网

C# 多线程中的操作无效

C# 多线程中的操作无效,c#,multithreading,asynchronous,async-await,C#,Multithreading,Asynchronous,Async Await,我需要两个并行执行的方法。工作改变无限循环中的数据。Represente也将更改的数据放入无限循环内的文本框中 Log log = Log.GetInstance; //singleton private void Work() { while (true) { //changing log } } private async void Represent() { await Task.Run

我需要两个并行执行的方法。工作改变无限循环中的数据。Represente也将更改的数据放入无限循环内的文本框中

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;在多个线程中生成错误无效操作:尝试从创建控件文本框的线程访问控件文本框。如何解决这个问题?提前谢谢。
由于无限循环,建议的.NET4.5方法不起作用

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

请看下面的示例:
对于跨线程更改,您需要调用

使用此代码:

仅用于ui中的元素,如文本框、组合框等,。。。。。 对于公共元素,您不需要这个

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

希望这个错误消息不是字面上所说的