0

I need two methods to be executing in parallel. Work() changes data inside infinite loop. Represent puts the changed data in the TextBox inside the infinite loop as well.

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

The problem is that textBox.Text = str; generates an error "invalid operation in multiple threads: attempt to access the control "textBox" from a thread in which it was created". How to solve that problem? Thanks in advance. P.S. Suggested method here for .NET 4.5 doesn't work because of the infinite loop.

Community
  • 1
  • 1
Denis Lolik
  • 299
  • 1
  • 4
  • 11

2 Answers2

-1

Attempt to access member of System.Windows.Forms.Control from different thread than UI thread will cause cross-thread exception.

Take a look at the this: How to update the GUI from another thread in C#?

Community
  • 1
  • 1
ak92
  • 41
  • 9
-1

for cross thread changing you need to invoking

use this code :

use this just for elements are in ui like textbox,combobox ,..... for public elements you don't need this

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

for your sample :

    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();
        }
Shahrooz Ansari
  • 2,637
  • 1
  • 13
  • 21