2

I am entering someone else's codebase in c# as a previously c++ coder. All over his code I find snippets that look like this:

MethodInvoker invoker = new MethodInvoker
      (delegate()
      {
        ...
      }
      );
try
{
   this.Invoke(invoker);
}
catch (Exception x)
{
  ...
}

My question is: Is there any reason to be using a delegate and then the try-catch? Can the code inside the curly braces on the third to fifth lines not just be placed inside that try catch? Is there some nuance of c# I do not yet know?

devduder
  • 394
  • 1
  • 10
rspencer
  • 2,651
  • 2
  • 21
  • 29

2 Answers2

5

This does not just invoke the delegate but passes it to a method called Invoke.

It's more of a nuance of the UI framework/enviroment your working with. In WinForms for example, there is only one GUI thread that can change UI controls' state. If you want to change a control's state from some other thread, you need to call Invoke method and pass a delegate, just like in your example. Calling Invoke basically means "run this delegate on the GUI thread".

See these questions: How to update the GUI from another thread in C#? Invoke in Windows Forms

And Control.Invoke documentation: http://msdn.microsoft.com/en-us/library/a1hetckb.aspx

Community
  • 1
  • 1
qbik
  • 5,502
  • 2
  • 27
  • 33
0

what you are doing here is defining a simple anonymous method that will be invoked later on winform's Control thread

MethodInvoker invoker = new MethodInvoker
      (delegate()
      {
        ...
      }
      );

what you are doing next is the execution of the anonymous method

try
{
   this.Invoke(invoker);
}
catch (Exception x)
{
  ...
}

Can the code inside the curly braces on the third to fifth lines not just be placed inside that try catch?

yes you can just do something like this (MethodInvoker)

try
    {
       this.Invoke((MethodInvoker)delegate()
      {
       //
      }
      ));
    }
    catch (Exception x)
    {
      ...
    }
BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47