0

I have a delegate

public delegate bool Controller_PDF_FileDone(object sender, 
  ControllerTaskEventArgs e);

And an event

public event Controller_PDF_FileDone On_Controller_PDF_FileDone;

I need to use this "event" to call the method, Please let me know how.

Thanks in advance

Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89
Varun
  • 426
  • 3
  • 7
  • 18
  • In the class that register on the event, you need to create a function - this function signature/parameters must be like your delegate, meaning create a function that return bool and accept object sender, ControllerTaskEventArgs e as parameters. then register the event with that delegate (function you just created). and when this event is fired, it will call your delegate – ilansch Jun 27 '13 at 12:08
  • Think of an event as a list of pointers to functions, and all functions must be as the delegate signature (same return type/parameters). when you fire the event, all the delegates will be called and receive the same parameters. – ilansch Jun 27 '13 at 12:10

1 Answers1

2

Invoking event (from the same class where it is declared):

var e = On_Controller_PDF_FileDone;
if (e != null) {
  e.Invoke(this, new ControllerTaskEventArgs());
}

Subscribing to an event (from the same class where it is declared):

On_Controller_PDF_FileDone += new Controller_PDF_FileDone(
  YourHandlingMethod_On_Controller_PDF_FileDone);
Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89
  • Unless you have a good reason not to, you should probably capture the event in a variable first and use that in the comparison and call (`var e = On_Controller_PDF_FileDone; if (e != null) e.Invoke(...);`). Unless specifically documented otherwise, it's generally okay to subscribe or unsubscribe to events from threads, so `On_Controller_PDF_FileDone` could change between the comparison to `null` and the `Invoke`. –  Jun 27 '13 at 12:08
  • @hvd you are right. this is a well known Best Practice to set the handler in a var and then check if null. http://stackoverflow.com/questions/3668953/raise-event-thread-safely-best-practice – ilansch Jun 27 '13 at 12:11
  • Edited to encourage "Best Practices". – Ondrej Svejdar Jun 27 '13 at 12:18