Search code examples
c#.netmultithreadingbegininvoke

Why would InvokeRequired=False via a Delegate.BeginInvoke?


For what reasons would this.InvokeRequired equal False within InitUIState(), as this new thread is being created via a delegate?

My problem is that my label is never being set and this.BeginInvoke() is never executing, I imagine it's due to the fact InvokeRequired = False.

    private delegate void BackgroundOperationDelegate(ViewMode mode);
    private BackgroundOperationDelegate backgroundOperationDelegate;

    private void FormControlPanel_Load(object sender, EventArgs e)
    {
        Init();
    }

    private void Init() {
        this.backgroundOperationDelegate = this.InitUIState;
        this.backgroundOperationDelegate.BeginInvoke(mode, null, null);
    }

    private void InitUIState(ViewMode mode)
    {
        // .. other business logic only here relevant
        // to the worker process ..
        this.BeginInvoke((MethodInvoker)delegate
        {
            this.labelProgramStatus.Text = CONSOLE_IDLE_STATUS;
        });
    }

I use this pattern time and time again, but for some reason, this time it's not executing :P (and yes there is only one instance of InitUIState() ever being called, that being from the delegate)

Thanks guys.

Images verifying two distinct threads:
http://imgur.com/mq12Wl&X5R7G
http://imgur.com/mq12W&X5R7Gl

Follow up question: Is this an unpreferred way of creating threads? I've just always found it so simple and lightweight. Perhaps I should be using thread.Start() and I will avoid these issues?


Solution

  • Your 2nd BeginInvoke will throw an Exception.

    Try

    private void InitUIState(ViewMode mode)
    {
        if (this.InvokeRequired)
        {
            this.BeginInvoke((MethodInvoker)delegate
            {
                InitUIState(mode);
            });
        }
        else
        {
            this.labelProgramStatus.Text = CONSOLE_IDLE_STATUS;
        }
    }