3

Possible Duplicate:
MethodInvoker vs Action for Control.BeginInvoke

    ThreadPool.QueueUserWorkItem(x =>
        {
            //get dataset from web service

            BeginInvoke(new Action(() => { 
                //fill grid
            }));

            BeginInvoke(new MethodInvoker(() => {
                //fill grid
            }));
        });

In C# 2.0 I was using allot the MethodInvoker to update the UI from a background thread, will it be wise to switch to Action when using under BeginInvoke? Is it faster or safer to use Action?

Community
  • 1
  • 1
Stefan P.
  • 9,489
  • 6
  • 29
  • 43
  • 1
    I'm kind of baffled by the people suggesting that he use neither. Are they using a different C# compiler than me? Mine makes me pass something deriving from `System.Delegate`. See http://stackoverflow.com/questions/253138/anonymous-method-in-invoke-call/253150#253150 – mqp Nov 11 '10 at 16:13
  • A similar question was already asked and answered here on stackoverflow http://stackoverflow.com/questions/1167771/methodinvoker-vs-action-for-control-begininvoke – Sam Nov 11 '10 at 16:07

2 Answers2

2

It really doesn't make a difference, as both are simply delegate types which take no parameters and don't return a value. However, in terms of naming semantics, MethodInvoker is specific to WinForms and should therefore be limited to that scope. Action is all-purpose and can be used in any area of the framework.

Bradley Smith
  • 13,353
  • 4
  • 44
  • 57
1

They are both delegates, and identical to each other in definition (grabbed from MSDN):

public delegate void MethodInvoker()
public delegate void Action()

So at the IL level they should be pretty much identical. So I doubt it matters much which one you use. Action is more universal and more likely to be understood by more developers, but MethodInvoker does have a more descriptive name. Go with whichever one feels better to you.

But as davidsoa points out, you can skip them both and just use a lambda directly.

Matt Greer
  • 60,826
  • 17
  • 123
  • 123