Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a value from an Event -- is there a Good Practice for this?

I'm doing a small multi-threaded app that uses asynchronous TCP sockets, but I will get to the point: I'm using a custom event to read a value from a form and the delegate used by the event returns a string when finished.

My question here is: is that correct? is it OK to return values from the events? or is there a better way to do this? (like using a simple delegate to the form to read the values)

like image 477
Hugo Avatar asked Jul 30 '09 23:07

Hugo


People also ask

Can an event return a value?

Firing an event is a one-way signal. By default most event handlers return void , because single event may have several subscribers, and return value could become ambiguous. However, it is possible for handlers to return values. Simple delegates may have any return type.

How do you return a variable from a function?

To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.

What is return type of event?

Events are delegates with a signature that takes an object and an eventargs and returns nothing (Void/Null). Event handlers are subroutines with the same method signature. So the return type is Void, or in other words, there is no return type.

What is EventArgs C#?

EventArgs is also the class you use when an event does not have any data associated with it. When you create an event that is only meant to notify other classes that something happened and does not need to pass any data, include the EventArgs class as the second parameter in the delegate. You can pass the EventArgs.


1 Answers

It's often awkward to return values from events. In practice, I've found it much easier to include a writable property on a set of custom EventArgs that is passed to the event, and then checked after the event fires -- similar to Cancel property of the WinForms FormClosing event.

like image 164
Dustin Campbell Avatar answered Sep 21 '22 17:09

Dustin Campbell