I’ve inherited code where BeginInvoke is called from the main thread (not a background thread, which is usually the pattern). I am trying to understand what it actually does in this scenario.
Does the method being called in the BeginInvoke get in line of messages that come down to the window? The docs say asynchronously, so that is my assumption.
How does the framework prioritize when to kick off the method called by BeginInvoke?
Edit: The code looks like this:
System.Action<bool> finalizeUI = delegate(bool open)
{
try
{
// do somewhat time consuming stuff
}
finally
{
Cursor.Current = Cursors.Default;
}
};
Cursor.Current = Cursors.WaitCursor;
BeginInvoke(finalizeUI, true);
This is happening in the Form_Load event.
edit
Now that we see the code, it’s clear that this is just a way to move some initialization out of Form_Load but still have it happen before the user can interact with the form.
The call to
BeginInvokeis inside Form_load, and is not called on another object, so this is a call to Form.BeginInvoke. So what’s happening is this.original post below
I depends on the object that you call BeginInvoke on. If the object is derived from
Controlthen Control.BeginInvoke will run on the thread that created the control. See JaredPar’s answer.But there is another pattern for the use of BeginInvoke. if the object is a delegate, then BeginInvoke runs the callback on a separate thread, one that may be created specifically for that purpose.
This pattern is one reason that BeginInvoke is called from the main thread rather than from a background thread.