-2

I want to update the UI from another class in non-UI thread.

But I can not call "BeginInvoke" in Test class directly.

How to solve it...

private void Form1_Load(object sender, EventArgs e)
{
    Task.Run(() =>
    {
        Test.Set(textBox1);
    });
}

public class Test
{       
    public static void Set(TextBox textBox)
    {
        // ↓Exception...
        textBox.Text = "ABCD";
    }
}
ChiaHsien
  • 315
  • 1
  • 3
  • 10
  • 1
    The form should be responsible for updating its own UI. It should not be exposing its private controls externally like that. Additionally, when using the TPL you shouldn't be using `invoke` at all (at least in typical situations). You should be relying on the fact that awaiting a task schedules the continuation to run on the UI thread to handle all of your UI marshaling. – Servy Mar 15 '18 at 15:41
  • In addition to what @Servy said, could you please clarify why "can not call `BeginInvoke` in Test class directly" (assuming you are talking about [`Control.BeginInvoke`](https://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke(v=vs.110).aspx) ) – Alexei Levenkov Mar 15 '18 at 15:45
  • "A question properly asked is a question half solved"-please keep this in mind before posting :) – Software Dev Mar 15 '18 at 15:46
  • are both of them in the same class ? is`Test` a nested class ? – Software Dev Mar 15 '18 at 15:48
  • @AlexeiLevenkov Your reply awoke me. I got it...Thank you very very much:). – ChiaHsien Mar 15 '18 at 15:50
  • 1
    @ChiaHsien Doing that is just going to result in you having even more problems. You don't want to try to figure out how to call `Invoke` from a class that has no business editing UI objects. – Servy Mar 15 '18 at 15:52

1 Answers1

-1

According to AlexeiLevenkov's reply.

I modified my code like below and it work well.

public static void Set(TextBox textBox, string text)
{
        textBox.BeginInvoke(new Action(() => { textBox.Text = text; }));
}
ChiaHsien
  • 315
  • 1
  • 3
  • 10