Best practices with events in C# - c#

In C#, you can have a return value in your event function. However, you only receive the return value of the last event. Also, there doesn't appear to be a way to get the return value of the previous event.
What are some good practices? Should I always use void? From my limited experience if I want to chain values must I use ref?
How might I write an event? I wanted to use Func<ref t, returnT>, but ref is illegal there, and I imagine action is the same way. (I ended up with the below). Is there a way to make the event one line instead of two when using a ref?
delegate int FuncType(ref int a);
static event FuncType evt;
static void Main(string[] args)
{
evt += foo;
var aa = 1;
var a = evt(ref aa);
evt += bar;
var bb = 1;
var b = evt(ref bb);
}
static int foo(ref int a)
{
a = a*3;
return a;
}
static int bar(ref int a)
{
a=a +1;
return a;
}

As said you can use GetInvocationList which will allow you to call each method individually and process returned data.
But before that please consider using EventHandler<T> with EventArgs.
You can have "everything" you need to be returned in EventArgs.
Check this sample code :
public class BalanceChangedEventArgs : EventArgs
{
public readonly double OldBalance;
public readonly double NewBalance;
public BalanceChangedEventArgs(double oldB, double newB)
{
OldBalance = oldB;
NewBalance = newB;
}
}
public class Account
{
private double balance;
public EventHandler<BalanceChangedEventArgs> balanceChanged;
protected void OnBalanceChanged(BalanceChangedEventArgs eArgs)
{
if (balanceChanged != null)
balanceChanged(this, eArgs);
}
public double Balance
{
get { return balance; }
set
{
if (balance == value)
return;
OnBalanceChanged(new BalanceChangedEventArgs(balance, value));
balance = value;
}
}
}

Don't confuse "event" with "callback". If you're wanting to provide a "hook" for customization, then consider one of the following:
A base class with virtual methods for hooks.
An interface for a callback object passed in to your constructor or accessed via a property.
A delegate passed in to your constructor or accessed via a property.
If you've considered the above, and still want to use an event, then you could include the "result" as part of your event argument type, e.g., e.Result or e.Handled. You still have the issue of multiple event handlers possibly overwriting each other's values, so you should combine that approach with iterating the invocation list as suggested by other answers. Either collate all the results or have an "early exit" strategy like what is used for e.Handled.

You may want to look at Microsoft's documentation for Event Design.

If you want to get the return values when an event has multiple subscribers, use Delegate.GetInvocationList. Then you can say
foreach(FuncType d in evt.GetInvocationList()) {
int value = d(parameter);
// do something with value
}
However, in general, it's best to avoid return values in event handlers.

The 'best practice' is to only use void eventhandlers. Precisely because of the last-value-only problem.
If you want combined results, define an EventArgs descendant with appropriate properties. Use a list or sum values or something.

Related

Getting all results from Func call

The concept of delegates aren't too new to me but I cannot seem to find out how to get all results from a Func delegates. More specifically, I have a class that has a Func delegate that returns a type bool. Something like this...
private Func<Employee, Shift, bool> qualificationCheckCallback;
There are both 'register' and 'unregister' methods for the callback as well. My goal is to see if any of the methods stored in the delegate return false when invoked later in code. Any insight you may have on this issue is much appreciated! Thanks.
You are using the wrong pattern. I'd recommend storing a list of these delegates and iterating over the list, rather than using multidelegates to call multiple targets.
You can make this work (if you need to) by changing the signature to include a "state" variable that is passed by reference to each caller:
private Action<Employee, Shift, QualCheckState> qualificationCheckCallback;
public class QualCheckState { public bool Passed { get; set; } }
// Call it thus:
var state = new QualCheckState { Passed = true }; // Hope for the best
qualificationCheckCallback(someEmployee, someShift, state);
if (state.Passed) {
// Assume everyone passed
}
Keep in mind, this requires the callees to honor the signature, and not overwrite anyone else's failed state:
public void SomeCallee(Employee e, Shift s, State state) {
// If some other check failed, don't bother doing our check.
if (!state.Passed) return;
// Do some check here
if (checkFailed) state.Passed = false;
}
Of course, you can also extend this pattern to make it safer:
public class QualCheckState {
private List<bool> _results = new List<bool>();
public bool Passed { get { return _results.All(s => s); }
public void RecordResult(bool result) {
_results.Add(result);
}
}
As mentioned in Andrew's answer, if you simply invoke qualificationCheckCallback like a normal method, you'll only get back the return value from one of the methods. For this reason, it's pretty unusual to have multicast delegates that have a return value.
If your goal is to see if at least one of the methods stored in your delegate returns false, you'll need to invoke the methods individually. Here is one way to do that using the Delegate.GetInvocationList() method:
bool hasAtLeastOneFalse = false;
if (qualificationCheckCallback != null)
{
foreach(var f in qualificationCheckCallback.GetInvocationList()
.Cast<Func<Employee, Shift, bool>>())
{
if (!f(employee, shift))
{
hasAtLeastOneFalse = true;
// break; // If you don't care about invoking all delegates, you can choose to break here.
}
}
}
Console.WriteLine(hasAtLeastOneFalse);
I'm not suggesting this is a good practice, but it can be done.
A quick search on MSDN found this thread:
https://social.msdn.microsoft.com/Forums/en-US/38a638fe-4a7d-44d6-876c-729d90c20737/how-to-get-return-value-from-delegate?forum=csharplanguage
The problem with events is that the return values cannot be fully
trusted. You will get only one return value no matter how many
subscribers that you have for the event. The central issue is that
you cannot reliably determine which subscriber produced the return
value. The beauty of the .NET Event Model is the anonymity that it
uses. That means event subscribers are completely abstracted from the
event publishers.

Understanding the event usage wrt delegates and registration methods

I am trying to understand the delegates and events, so far I know the concepts.
I have a question in mind and want to know if I am right.
There is a class Car. We create a public delegate (CarHandler), then we create a private member of delegate type (ListofMethods), then we create method for registering methods with this member (RegistorMethods) in this we say ListofMethods+=incoming parameter.
Then, in main program we create methods with signature same as that of the delegate(signature is return type void and parameter is string). Then, we create object of Car class. Then we register the method/methods with the delegate (method is console.writeline(incomming parameter)). Then when we invoke this class. Now, based on where in the class the ListofMethods is invoked (example:ListofMethods("Hey There");), accordingly the RegistoredMethods will fire.
So the advantage of using events instead of above example is that :
I know that we can create multiple events of the same delegate type with out creating more registration methods.
Case 1 is using only delegates and no events. And case 2 is using events. Then, In case 1, all the registered methods would get the same text as invoked by ListofHandler. To create more events (events here mean the general english meaning and not the c# events) in Case 1 we would need to create more delegate members, more methods for registering new methods with this delegate member. However, in Case of EVENTS (case 2) the different events can give their own text and the instance can then register with the event it needs and it will get it fired.
In CASE 1 we would need to create more delegate members for raising multiple events(not C# events, general English meaning), where as in case of CASE 2 (events) it is enough to create only 1 delegate member. Is that right?
Question:
Is the above para correct way to implement a CASE 3, that is like case 2, but only using delegates and not events. Please can you write a note on this in your answer
If not understood then you can ask me question. Please help me clear my doubt here.
Code for CASE 1:
public class Car
{
// 1) Define a delegate type.
public delegate void CarEngineHandler(string msgForCaller);
// 2) Define a member variable of this delegate.
//this can be public, and if public then we can avoid writing the below RegisterWithCarEngine method, but it is not safe
//because user can mess the values and call custom strings, etc
private CarEngineHandler listOfHandlers;
// 3) Add registration function for the caller.
public void RegisterWithCarEngine(CarEngineHandler methodToCall)
{
//listOfHandlers = methodToCall;
listOfHandlers += methodToCall;
}
// Internal state data.
public int CurrentSpeed { get; set; }
public int MaxSpeed { get; set; }
public string PetName { get; set; }
// Is the car alive or dead?
private bool carIsDead;
// Class constructors.
public Car()
{
MaxSpeed = 100;
}
public Car(string name, int maxSp, int currSp)
{
CurrentSpeed = currSp;
MaxSpeed = maxSp;
PetName = name;
}
// 4) Implement the Accelerate() method to invoke the delegate's
// invocation list under the correct circumstances.
public void Accelerate(int delta)
{
// If this car is "dead," send dead message.
if (carIsDead)
{
if (listOfHandlers != null)
listOfHandlers("Sorry, this car is dead...");
}
else
{
CurrentSpeed += delta;
// Is this car "almost dead"?
if (10 == (MaxSpeed - CurrentSpeed) && listOfHandlers != null)
{
listOfHandlers("Careful buddy! Gonna blow!");
}
if (CurrentSpeed >= MaxSpeed)
carIsDead = true;
else
Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed);
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Delegates as event enablers *****\n");
// First, make a Car object.
Car c1 = new Car("SlugBug", 100, 10);
// Now, tell the car which method to call
// when it wants to send us messages.
c1.RegisterWithCarEngine(new Car.CarEngineHandler(OnCarEngineEvent));
// Speed up (this will trigger the events).
Console.WriteLine("***** Speeding up *****");
for (int i = 0; i < 6; i++)
c1.Accelerate(20);
Console.ReadLine();
Car c2 = new Car("SlugBug1", 100, 10);
// Speed up (this will trigger the events).
Console.WriteLine("***** Speeding up *****");
for (int i = 0; i < 6; i++)
c2.Accelerate(20);
Console.ReadLine();
}
// This is the target for incoming events.
public static void OnCarEngineEvent(string msg)
{
Console.WriteLine("\n***** Message From Car Object *****");
Console.WriteLine("=> {0}", msg);
Console.WriteLine("***********************************\n");
}
}
Code for CASE 2:
public class Car
{ // This delegate works in conjunction with the
// Car's events.
public delegate void CarEngineHandler(string msg);
// This car can send these events.
public event CarEngineHandler Exploded;
public event CarEngineHandler AboutToBlow;
...
}
public void Accelerate(int delta)
{
// If the car is dead, fire Exploded event.
if (carIsDead)
{
if (Exploded != null)
Exploded("Sorry, this car is dead...");
}
else
{ CurrentSpeed += delta;
// Almost dead?
if (10 == MaxSpeed - CurrentSpeed && AboutToBlow != null)
{
AboutToBlow("Careful buddy! Gonna blow!");
}
// Still OK!
if (CurrentSpeed >= MaxSpeed)
carIsDead = true;
else
Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed);
}
}
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Events *****\n");
Car c1 = new Car("SlugBug", 100, 10);
// Register event handlers.
c1.AboutToBlow += CarIsAlmostDoomed;
c1.AboutToBlow += CarAboutToBlow;
c1.Exploded += CarExploded;
Console.WriteLine("***** Speeding up *****");
for (int i = 0; i < 6; i++)
c1.Accelerate(20);
c1.Exploded -= CarExploded;
Console.WriteLine("\n***** Speeding up *****");
for (int i = 0; i < 6; i++)
c1.Accelerate(20);
Console.ReadLine();
public static void CarAboutToBlow(string msg) { Console.WriteLine(msg); }
public static void CarIsAlmostDoomed(string msg) { Console.WriteLine("=> Critical Message from Car: {0}", msg); }
public static void CarExploded(string msg) { Console.WriteLine(msg); }
}
Your two cases are nearly identical. The only material difference is that when you use an event in your class (i.e. "case 2"), and you don't implement it explicitly, the compiler automatically generates the field that you would have had to declare in "case 1", as well as the method to allow subscription/registration.
Something that often surprises people, even occasionally those who have been using C# for some time, is a statement like mine above:
and you don't implement it explicitly
What's that statement mean? Many people don't realize that, as with a property, it is possible to either let the compiler implement the member, or to do it yourself.
In the case of the property, you implement a get and/or a set method. In the case of an event, the methods are named add and remove. And of course, if you implement it yourself, you need to also provide the backing field or other mechanism to track subscribers (just like in a property).
So, what's this all mean in your specific example? Well, to me it means that if you have event-like semantics, then you definitely should just go ahead and implement that as an actual event member. The code will all basically compile down to equivalent IL regardless of which way you do it, but using an event takes advantage of the language's high-level abstraction. This makes the code easier both to read and write, and so makes it more maintainable and less likely to contain bugs.
You can keep in mind the approach in "case 1", in case you wind up in a situation where declaring an event doesn't work (e.g. some kind of interop with a platform or API that doesn't deal with or support the .NET event paradigm). But in most situations, event is the way to go.
It seems that part of your concern is the question of the delegate members (i.e. the declared delegate types). Frankly, you have this issue regardless of which way you approach the problem. If you have a way of reusing a single delegate type for multiple event members in a class, then you can also reuse that single delegate type for the explicit field-and-registration-method approach ("case 1").
In most cases, you should not be declaring your own delegate type anyway. Just use e.g. EventHandler<T>, or one of the general purpose Action or Func types.
The difference between your two cases basically boil down to this difference:
Case 1
public class Car
{
void RegisterWithCarEngine(CarEngineHandler methodToCall);
}
Case 2
public class Car
{
event CarEngineHandler Exploded;
event CarEngineHandler AboutToBlow;
}
Case 1 is rather odd. There is nothing there to let a consumer of this class know what this method does - or when it will fire. Also, and perhaps more importantly, there is no way to detach then event handler.
Case 2 is more standard. It fits with the concept of giving a good naming convention and it is clear that these two members are events. It is therefore obvious to a consumer that they can attach and detach to these events.
You need to think about it a bit like if this where your design:
public class Car
{
void SetSpeed(string speedName, int speed);
int GetSpeed(string speedName);
}
I might then code it like this:
car.SetSpeed("Max", 50);
car.SetSpeed("Current", 10);
Console.WriteLine(car.GetSpeed("Max"));
Console.WriteLine(car.GetSpeed("Current"));
Now while this provide nominally the same functionality as your class - and same may argue that it offers even more functionality - it hides the functionality as seen by a consumer of the class.
It is far better to go with the interface provided by Case 2.
Just as a side note, you should always call your event code like this:
var x = Exploded;
if (x != null)
x("Sorry, this car is dead...");
It is possible that the delegates on Exploded can be removed between the null check and the call. The temporary assignment prevents that issue.

How to identify an anonymous function

I have a class that creates a List<Action<int>> and holds on to them until a later time. This class can add and remove delegates from this list. This works well as long as people don't get too fancy. To combat anonymous function (which can't be removed) I check against the target of the delegate being null. If its null I throw an exception. The problem comes in when there is an anonymous delegate that contains a function. This has a target, but is just as unremovable. The simplified code below illustrates my issues
public class MyDelegateContainer
{
List<Action<int>> m_Container = new List<Action<int>>();
public void Add(Action<int> del)
{
if (del.Target == null)
{
throw new Exception("No static handlers");
}
m_Container.Add(del);
}
public bool Remove(Action<int> del)
{
if (m_Container.Contains(del))
{
m_Container.Remove(del);
return true;
}
return false;
}
}
public class MyFakeActionClass
{
public void Test(int temp) { }
}
class Program
{
static void Main(string[] args)
{
bool removed = false;
int counter = 0;
MyDelegateContainer container = new MyDelegateContainer();
MyFakeActionClass fake = new MyFakeActionClass();
//container.Add(p => { }); //Throws, this is what I want to happen
container.Add(fake.Test); //Works, this is the use case
removed = container.Remove(fake.Test); //Works, this is the use case
Debug.Assert(removed);
container.Add(p => { fake.Test(p); counter++; }); //Works but I would like it not to
removed = container.Remove(p => { fake.Test(p); counter++; }); //doesn't work
Debug.Assert(removed);
}
}
I need some way to identify
p => { fake.Test(p); counter++; }
is an anonymous function so I can throw if someone tries it. Thanks for any help
EDIT: I should note that I could use an Action<int> variable for the anonymous function and everything would work, but the Add and Remove are never in the same scope in practice.
In your example, the caller is responsible from removing the handler. So, if the caller doesn't want to remove the handler, it won't get removed, no matter if the handler is an anonymous delegate/lambda or not.
My suggestion is to change the delegate container to something like this:
public class MyDelegateContainer
{
List<Action<int>> m_Container = new List<Action<int>>();
public Action Add(Action<int> del)
{
m_Container.Add(del);
return new Action(() =>
{
m_Container.Remove(del);
});
}
}
The caller is still responsible for removing the handler, but instead of passing the handler again to the container, it receives a "token" that it can save and use later to remove the handler.
There is no way to reliably determine whether a function is "anonymous" because all functions have names to the CLR. It's only anonymous within the language that generates it, and that's compiler-dependent. You may be able to determine the algorithm used by Microsoft's current C# compiler, only to have it stop working on C# 5 or Mono.
Since you want to prevent users of your type from writing code that uses it wrong, you just need to throw an exception at some point that will make their program crash. What I would do is throw the exception in the Remove function when the target delegate isn't found. At that point your users will still get a crash and the only way to fix it is to write the delegate in some way that it's removable.
As an added bonus, you will catch bugs where somebody tries to remove delegates twice or that were never added in the first place. The code would look like this:
public bool Remove(Action<int> del)
{
if (m_Container.Contains(del))
{
m_Container.Remove(del);
return true;
}
throw new ArgumentException("Attempt to remove nonexistent delegate");
}
I would use introspection to check the names of the methods.
Anonymous methods typically have very predictable names. (I don't remember the exact format, but run some tests, and it should be obvious).
The drawback would be that if anyone created a non-anonymous method, but decided to name it anonMethod123 (or whatever the format is...) It would be falsely rejected.
Of course you can remove an anonymous method, you just need to have a reference to the same anonymous method.
var myAnonymousMethod = p => { fake.Test(p); counter++; };
container.Add(myAnonymousMethod);
removed = container.Remove(myAnonymousMethod);
As jonnii suggested in a comment, another way you could implement it is with a dictionary:
public class MyDelegateContainer
{
Dictionary<string, Action<int>> m_Container =
new Dictionary<string, Action<int>>();
public void Add(string key, Action<int> del)
{
m_Container.Add(key, del);
}
public bool Remove(string key)
{
return m_Container.Remove(key);
}
}
Then you could easily remove a known delegate at some arbitrary point in your code just by knowing what name was used to add it:
container.Add("fake.Test", fake.Test);
removed = container.Remove("fake.Test");
Debug.Assert(removed);
container.Add("anon", p => { fake.Test(p); counter++; });
removed = container.Remove("anon"); // works!
Debug.Assert(removed);
Old question I know but I would think that this would be a current (and future) proofed way of checking if a method is anonymous:
bool isAnonymous = !System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(del.Method.Name);
The runtime name of the anonymous method would have to be invalid if used at compilation time to ensure that it didn't clash.

Delegates, Why? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
When would you use delegates in C#?
The purpose of delegates
I have seen many question regarding the use of delegates. I am still not clear where and WHY would you use delegates instead of calling the method directly.
I have heard this phrase many times: "The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked."
I don't understand how that statement is correct.
I've written the following examples. Let's say you have 3 methods with same parameters:
public int add(int x, int y)
{
int total;
return total = x + y;
}
public int multiply(int x, int y)
{
int total;
return total = x * y;
}
public int subtract(int x, int y)
{
int total;
return total = x - y;
}
Now I declare a delegate:
public delegate int Operations(int x, int y);
Now I can take it a step further a declare a handler to use this delegate (or your delegate directly)
Call delegate:
MyClass f = new MyClass();
Operations p = new Operations(f.multiply);
p.Invoke(5, 5);
or call with handler
f.OperationsHandler = f.multiply;
//just displaying result to text as an example
textBoxDelegate.Text = f.OperationsHandler.Invoke(5, 5).ToString();
In these both cases, I see my "multiply" method being specified. Why do people use the phrase "change functionality at runtime" or the one above?
Why are delegates used if every time I declare a delegate, it needs a method to point to? and if it needs a method to point to, why not just call that method directly? It seems to me that I have to write more code to use delegates than just to use the functions directly.
Can someone please give me a real world situation? I am totally confused.
Changing functionality at runtime is not what delegates accomplish.
Basically, delegates save you a crapload of typing.
For instance:
class Person
{
public string Name { get; }
public int Age { get; }
public double Height { get; }
public double Weight { get; }
}
IEnumerable<Person> people = GetPeople();
var orderedByName = people.OrderBy(p => p.Name);
var orderedByAge = people.OrderBy(p => p.Age);
var orderedByHeight = people.OrderBy(p => p.Height);
var orderedByWeight = people.OrderBy(p => p.Weight);
In the above code, the p => p.Name, p => p.Age, etc. are all lambda expressions that evaluate to Func<Person, T> delegates (where T is string, int, double, and double, respectively).
Now let's consider how we could've achieved the above without delegates. Instead of having the OrderBy method take a delegate parameter, we would have to forsake genericity and define these methods:
public static IEnumerable<Person> OrderByName(this IEnumerable<Person> people);
public static IEnumerable<Person> OrderByAge(this IEnumerable<Person> people);
public static IEnumerable<Person> OrderByHeight(this IEnumerable<Person> people);
public static IEnumerable<Person> OrderByWeight(this IEnumerable<Person> people);
This would totally suck. I mean, firstly, the code has become infinitely less reusable as it only applies to collections of the Person type. Additionally, we need to copy and paste the very same code four times, changing only 1 or 2 lines in each copy (where the relevant property of Person is referenced -- otherwise it would all look the same)! This would quickly become an unmaintainable mess.
So delegates allow you to make your code more reusable and more maintainable by abstracting away certain behaviors within code that can be switched in and out.
.NET Delegates: A C# Bedtime Story
Delegates are extremely useful, especially after the introduction of linq and closures.
A good example is the 'Where' function, one of the standard linq methods. 'Where' takes a list and a filter, and returns a list of the items matching the filter. (The filter argument is a delegate which takes a T and returns a boolean.)
Because it uses a delegate to specify the filter, the Where function is extremely flexible. You don't need different Where functions to filter odd numbers and prime numbers, for example. The calling syntax is also very concise, which would not be the case if you used an interface or an abstract class.
More concretely, Where taking a delegate means you can write this:
var result = list.Where(x => x != null);
...
instead of this:
var result = new List<T>();
foreach (var e in list)
if (e != null)
result.add(e)
...
Why are delegates used if everytime I
declare a delegate, it needs a method
to point to? and if it needs a method
to point to, why not just call that
method directly?
Like interfaces, delegates let you decouple and generalize your code. You usually use delegates when you don't know in advance which methods you will want to execute - when you only know that you'll want to execute something that matches a certain signature.
For example, consider a timer class that will execute some method at regular intervals:
public delegate void SimpleAction();
public class Timer {
public Timer(int secondsBetweenActions, SimpleAction simpleAction) {}
}
You can plug anything into that timer, so you can use it in any other project or applications without trying to predict how you'll use it and without limiting its use to a small handful of scenarios that you're thinking of right now.
Let me offer an example. If your class exposes an event, it can be assigned some number of delegates at runtime, which will be called to signal that something happened. When you wrote the class, you had no idea what delegates it would wind up running. Instead, this is determined by whoever uses your class.
One example where a delegate is needed is when you have to modify a control in the UI thread and you are operating in a different thread. For example,
public delegate void UpdateTextBox(string data);
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
...
Invoke(new UpdateTextBox(textBoxData), data);
...
}
private void textBoxData(string data)
{
textBox1.Text += data;
}
In your example, once you've assigned a delegate to a variable, you can pass it around like any other variable. You can create a method accepting a delegate as a parameter, and it can invoke the delegate without needing to know where the method is really declared.
private int DoSomeOperation( Operations operation )
{
return operation.Invoke(5,5);
}
...
MyClass f = new MyClass();
Operations p = new Operations(f.multiply);
int result = DoSomeOperation( p );
Delegates make methods into things that you can pass around in the same way as an int. You could say that variables don't give you anything extra because in
int i = 5;
Console.Write( i + 10 );
you see the value 5 being specified, so you might as well just say Console.Write( 5 + 10 ). It's true in that case, but it misses the benefits for being able to say
DateTime nextWeek = DateTime.Now.AddDays(7);
instead of having to define a specifc DateTime.AddSevenDays() method, and an AddSixDays method, and so on.
To give a concrete example, a particularly recent use of a delegate for me was SendAsync() on System.Net.Mail.SmtpClient. I have an application that sends tons and tons of email and there was a noticeable performance hit waiting for the Exchange server to accept the message. However, it was necessary to log the result of the interaction with that server.
So I wrote a delegate method to handle that logging and passed it to SendAsync() (we were previously just using Send()) when sending each email. That way it can call back to the delegate to log the result and the application threads aren't waiting for the interaction to finish before continuing.
The same can be true of any external IO where you want the application to continue without waiting for the interaction to complete. Proxy classes for web services, etc. take advantage of this.
You can use delegates to implement subscriptions and eventHandlers.
You can also (in a terrible way) use them to get around circular dependencies.
Or if you have a calculation engine and there are many possible calculations, then you can use a parameter delegate instead of many different function calls for your engine.
Did you read http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx ?
Using your example of Operations, imagine a calculator which has several buttons.
You could create a class for your button like this
class CalcButton extends Button {
Operations myOp;
public CalcButton(Operations op) {
this.myOp=op;
}
public void OnClick(Event e) {
setA( this.myOp(getA(), getB()) ); // perform the operation
}
}
and then when you create buttons, you could create each with a different operation
CalcButton addButton = new CalcButton(new Operations(f.multiply));
This is better for several reasons. You don't replicate the code in the buttons, they are generic.
You could have multiple buttons that all have the same operation, for example on different panels or menus. You could change the operation associated with a button on the fly.
Delegates are used to solve an Access issue. When ever you want to have object foo that needs to call object bar's frob method but does not access to to frob method.
Object goo does have access to both foo and bar so it can tie it together using delegates. Typically bar and goo are often the same object.
For example a Button class typically doesn't have any access to the class defines a Button_click method.
So now that we have that we can use it for a whole lot things other than just events. Asynch patterns and Linq are two examples.
It seems many of the answers have to do with inline delegates, which in my opinion are easier to make sense of than what I'll call "classic delegates."
Below is my example of how delegates allow a consuming class to change or augment behaviour (by effectively adding "hooks" so a consumer can do things before or after a critical action and/or prevent that behaviour altogether). Notice that all of the decision-making logic is provided from outside the StringSaver class. Now consider that there may be 4 different consumers of this class -- each of them can implement their own Verification and Notification logic, or none, as appropriate.
internal class StringSaver
{
public void Save()
{
if(BeforeSave != null)
{
var shouldProceed = BeforeSave(thingsToSave);
if(!shouldProceed) return;
}
BeforeSave(thingsToSave);
// do the save
if (AfterSave != null) AfterSave();
}
IList<string> thingsToSave;
public void Add(string thing) { thingsToSave.Add(thing); }
public Verification BeforeSave;
public Notification AfterSave;
}
public delegate bool Verification(IEnumerable<string> thingsBeingSaved);
public delegate void Notification();
public class SomeUtility
{
public void SaveSomeStrings(params string[] strings)
{
var saver = new StringSaver
{
BeforeSave = ValidateStrings,
AfterSave = ReportSuccess
};
foreach (var s in strings) saver.Add(s);
saver.Save();
}
bool ValidateStrings(IEnumerable<string> strings)
{
return !strings.Any(s => s.Contains("RESTRICTED"));
}
void ReportSuccess()
{
Console.WriteLine("Saved successfully");
}
}
I guess the point is that the method to which the delegate points is not necessarily in the class exposing the delegate member.

when an event has multiple subscribers, how do I get the return value for each subscriber?

The code looks like below:
Clock:
public class Clock
{
public event Func<DateTime, bool> SecondChange;
public void Run()
{
for (var i = 0; i < 20; i++)
{
Thread.Sleep(1000);
if (SecondChange != null)
{
//how do I get return value for each subscriber?
Console.WriteLine(SecondChange(DateTime.Now));
}
}
}
}
DisplayClock:
public class DisplayClock
{
public static bool TimeHasChanged(DateTime now)
{
Console.WriteLine(now.ToShortTimeString() + " Display");
return true;
}
}
LogClock:
public class LogClock
{
public static bool WriteLogEntry(DateTime now)
{
Console.WriteLine(now.ToShortTimeString() + " Log");
return false;
}
}
To run the code:
var theClock = new Clock();
theClock.SecondChange += DisplayClock.TimeHasChanged;
theClock.SecondChange += LogClock.WriteLogEntry;
theClock.Run();
The other questions are:
Is it good practice for each subscriber to return a value?
Is it good practice to just declare Action/Func as the event return type instead of manually declaring a delegate?
Use Delegate.GetInvocationList.
if (SecondChange != null)
{
DateTime now = DateTime.Now;
foreach (Delegate d in SecondChange.GetInvocationList())
{
Console.WriteLine(d.DynamicInvoke(now));
}
}
is it good practice to just use Action/Func instead of manually declaring a delegate?
Yes. But I will point out that the best practice is for events to use EventHandler<T> instead of Func<..., TResult>. EventHandler<T> does not support return values, but you are somewhat justified in that there are a few .NET events that have return values. I would consider it better to have a settable property in a custom EventArgs subclass that you use as your T. This is the pattern we see in things like KeyEventArgs.Handled. In this way, you can use EventHandler<T> and the subscribers can also coordinate their responses to a limited extent by getting and setting this property.
I think it is perfectly fine to use Action/Func instead of the delegate.
BUT Events are not supposed to be used like that.
They are triggered at indefinite time point, so you just don't know all the parameters.
What you really need is probably:
Use polymorphism for clock.
Use visitor/subscriber/observer patterns to get their values.
So the code will look like:
var theClock = new Clock();
theClock.AddSecondsSubscriber(new DisplayClock());
theClock.AddSecondsSubscriber(new LogClock());
theClock.RunAndExecuteVisitors( theBoolResultYouNeed => Console.WriteLine(theBoolResultYouNeed) );

Categories

Resources