How to update text fields in main stream from another stream?

New in C # is so naked with me. How do you update text fields and labels in the main thread from a new thread executing another class.

MainForm.cs (Main Stream)

public partial class MainForm : Form
{
    public MainForm()
    {
        Test t = new Test();

        Thread testThread = new Thread(new ThreadStart(t.HelloWorld));
        testThread.IsBackground = true;
        testThread.Start();
    }

    private void UpdateTextBox(string text)
    {
        textBox1.AppendText(text + "\r\n");
    }

}

public class Test
{
    public void HelloWorld()
    {
        MainForm.UpdateTextBox("Hello World"); 
        // How do I execute this on the main thread ???
    }
}

I reviewed the examples here, but did not seem to understand. Please can someone give some good links.

I started fresh again, so I didn't mess up my code. If someone would like to give a working example with my example, that would be great.

Also, if I had to update several objects, such as text fields and labels, etc. (not all at the same time), what would be the best way to do this, having a method for each text field or is there a way to do this using one method? As I said, I'm new, so I’m talking slowly :)

+5
3

Invoke BeginInvoke,

Invoke((MethodInvoker)delegate {
    MainForm.UpdateTextBox("Hello World"); 
});

@tiptopjones , , . HelloWorld , ParameterizedThreadStart, Thread.Start. , .

public class MainForm : Form {
    public MainForm() {
        Test t = new Test();

        Thread testThread = new Thread((ThreadStart)delegate { t.HelloWorld(this); });
        testThread.IsBackground = true;
        testThread.Start();
    }

    public void UpdateTextBox(string text) {
        Invoke((MethodInvoker)delegate {
            textBox1.AppendText(text + "\r\n");
        });
    }
}

public class Test {
    public void HelloWorld(MainForm form) {
        form.UpdateTextBox("Hello World"); 
    }
}

, - :

Thread testThread = new Thread(() => t.HelloWorld(this));
+6

BeginInvoke, .

, , Invoke.

, ; Test .


BackgroundWorker , ReportProgress; .

+4

WinForms SynchronizationContext

public partial class MainForm : Form
{
    SynchronizationContext ctx;

    public MainForm()
    {
        ctx = SynchronizationContext.Current;

        Test t = new Test();

        Thread testThread = new Thread(new ThreadStart(t.HelloWorld));
        testThread.IsBackground = true;
        testThread.Start();
    }

    private void UpdateTextBox(string text)
    {
        ctx.Send(delegate(object state)
        {
            textBox1.AppendText(text + "\r\n");

        },null);
    }    
}

public class Test
{
    public void HelloWorld()
    {
        MainForm.UpdateTextBox("Hello World"); 
        // How do I excute this on the main thread ???
    }
}
+1

All Articles