0

Addition after several closures of this question

NO, This question does not give the answer.

I tried it, I refer to it in my code, but it does not return from Invoke!


Original question

Until now, whenever I had any other thread who had to update something on the UI, I used InvokeRequired / BeginInvoke in a pattern like this.

void UpdateLabel(string txt)
{
    if (this.InvokeRequired)
    {
        this.BeginInvoke(new MethodInvoker(delegate() { UpdateLabel(txt);}));
        return;
    }
    this.label1.Text = txt;
}

Test usage:

var task = Task.Run(() => UpdateLabel("Hello World!"));
task.Wait();

The first time InvokeRequired is true, the second time it is false;

But now I need to do this with a method that has a return value. StackOverflow to the rescue!

Answer states:

  • Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.
  • Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.

And another question even gave an answer:

public static string readControlText(Control varControl)
{
    if (varControl.InvokeRequired)
    {
        return (string)varControl.Invoke(
               new Func<String>(() => readControlText(varControl)));
    }
    else
    {
        return varControl.Text;
    }
}

So I thought:

DialogResult AskPermission(string question)
{
    if (this.InvokeRequired)
    {
        return (DialogResult) this.Invoke(
                new MethodInvoker(delegate() { AskPermission(txt);}));
    }

    return MessageBox.Show(question, caption, MessageBoxButtons.YesNoCancel);
}

Alas, this does not work. First time InvokeRequired true, but no second time for InvokeRequired.

How to use Invoke / MethodInvoker?


Addition after several closures of this question

Can it be that I call it incorrectly in my test code:

var task = Task.Run( () => AskPermission("What should I do?");
Dialogresult dlgResult = task.Wait();
Harald Coppoolse
  • 24,051
  • 6
  • 48
  • 92
  • 1
    Since you're using the TPL already just use it in entirety rather than mixing in decades obsolete technologies in as well. This is one of the many reasons why the TPL is preferable, it assumes any operation may have a result to provide. – Servy Mar 09 '21 at 15:04

0 Answers0