Control.InvokeRequired changing throughout a method

475 Views Asked by At

Look at these screenshots. First shows a breakpoint in my code and shows current value of InvokeRequired.

Step 1

Seconds screenshot shows value of InvokeRequired after pressing F10 (step over) one time in debugger (IF statement content is not entered, ELSE is).

Step 2

What happens next, is InvalidOperationException on rtbOutput, because I try to change its fields in ReportProgress. Here is how I call OnProgressReported:

public event EventHandler<BuildProgressEventArgs> BuildProgresReported = delegate { };

public void InvokeReportBuildProgress(BuildProgress progress)
{
    BuildProgresReported.Invoke(this, new BuildProgressEventArgs(progress));
}

How is this even possible? Is there other, better way to detect if Invoke should be called?

Update:

I have changed method code to the following:

public void OnProgressReported( object caller, BuildProgressEventArgs progressEventArgs )
        {
            if( rtbOutput.InvokeRequired )
            {
                Debug.WriteLine($"Invoke was required on thread: #{Thread.CurrentThread.ManagedThreadId} named '{Thread.CurrentThread.Name}'");
                rtbOutput.BeginInvoke( new Action( () => OnProgressReported(caller, progressEventArgs) ) );
            }
            else
            {
                Debug.WriteLine($"Invoke was NOT required on thread: #{Thread.CurrentThread.ManagedThreadId} named '{Thread.CurrentThread.Name}'");
                if ( this.IsDisposed )
                {
                    throw new InvalidOperationException( "This form has been disposed" );
                }

                rtbOutput.Text = "abc";
                rtbOutput.Text = "xxx";
                //ReportProgress(progressEventArgs.Progress);
            }
        }

The only output is

Invoke was NOT required on thread: #15 named ''

and the method this throw an exception on line rtbOutput.Text = "abc";

HOWEVER! When the line rtbOutput.Text = "xxx"; is commented out, everything works fine, even though rtbOutput.Text = "abc"; is still present!

Update #2 - solution:

The problem was a window handle that was not yet created (I subscribe to an event right AFTER creating the window) I have to wait for handle to be created using

this.IsHandleCreated
0

There are 0 best solutions below