Multithreading how to invoke Action

I have some menu popup with action buttons. This is popup so it is made in new thread. I add event to created buttons something like this:

private StdProcedure m_ToInvoke;

public void AddButton()
{
    Button myChildTempButton = new Button();
    myChildTempButton.ItemClick += new ItemClickEventHandler((x, y) => 
    { 
       HidePopup(); m_ToInvoke = myOpp.Procedure; 
    });
 }

StdProcedure is delegate

 public delegate void StdProcedure();

And after close event:

 protected override void OnPopupClosed()
 {
    base.OnPopupClosed();
    if (m_ToInvoke != null) m_ToInvoke.Invoke();
 }

That doesn't work correctly. Sometime invoked operations stopped my another thread and I don't understand how it's works.

My question is what is the different between:

m_ToInvoke()
m_ToInvoke.Invoke()
m_ToInvoke.BeginInvoke()
m_ToInvoke.DynamicInvoke()

and what should I use here?

For me first and second is the same in effect.

Jon Skeet
people
quotationmark

  • m_ToInvoke() is just C# syntactic sugar for m_ToInvoke.Invoke()
  • m_ToInvoke.Invoke() executes the delegate synchronously, in the same thread
  • m_ToInvoke.BeginInvoke() schedules the delegate for invocation in a thread-pool thread; the returned IAsyncResult can be used to wait for it to complete, and you can also pass in a callback
  • m_ToInvoke.DynamicInvoke() is the only one of these methods to be declared by Delegate - it's similar to calling it by reflection, in that there's no compile-time safety for the number/type of the arguments etc.

Note that calling Invoke/BeginInvoke on a delegate is very different to calling Dispatcher.Invoke/BeginInvoke or Control.Invoke/BeginInvoke, which are to do with invoking a delegate within the UI thread for a WPF/WinForms app - although again, the Invoke version is synchronous and BeginInvoke is asynchronous.

people

See more on this question at Stackoverflow