1

I am calling a method "Foo(object s, Action action)" inside a library. Since, the function is itself involves some amount of execution time, i use CountDownEvents' to notify me when the function has done its job.

something like,

countdownEvent.Reset();


try
 {
     Foo(obj, ()=> countdownEvent.Signal());
 }
 catch(Exception e)
 {
    countdownEvent.Signal();
 }
 countdownEvent.Wait();

The part that I am not understanding is

  1. what is meant by () => countdownEvent.Signal() ? What is the "()=> " in particular stand for?
  2. Why did the method signature was not written Foo(object s, CountDownEvent event) and it can signal internally?
  3. I don't still really get an understanding of Action class. Googled a bit but just cant find some super simple examples to get started.

Any help is appreciated!

3 Answers3

3

() => countdownEvent.Signal() is a lambda expression.

In this particular situation is some kind of anonymous method that takes no parameters and has the same return type as countdownEvent.Signal().

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
2
  1. () => is a lambda construction (see C# Lambda ( => )). By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expression. But you can use it to write any kind on delegate implementations.
  2. You can specify the same code in the way you show, but using Action makes it more flexible. In first case it is a specific function, with declared behavior. In second - it is some activity, which you can change according to the logic of your program.
  3. Action is just a delegate, which is declaring some dynamic behaviour. It encapsulates a method that has parameters and does not return a value. To reference a method that has parameters and returns a value, use the generic Func delegate instead. It is often used, when your class expects some behaviour, and you want your class consumers to declare this behaviour by their own.

UPDATED: According to VikciaR comment

Community
  • 1
  • 1
Alex
  • 8,827
  • 3
  • 42
  • 58
  • 1
    I would correect your 3. Action has not single implementation: there is multiple implementations with different number of parameters. Func has not only parameters, but has also return value. – VikciaR Jul 18 '13 at 07:27
1
  1. This is what is called Lambda expression. You can look to it as simple inline method. ()=> means, that this method doesn't have parameters. (string x)=> would mean - one parameter.
  2. Events and lambda expressions is similar concepts (Lambda expression is evolution from delegates). Read here.
  3. MSDN is the best :-)
VikciaR
  • 3,324
  • 20
  • 32