Before I reinvent the wheel...
This is just an EXAMPLE for describing the problem -- let's say you have a backend with collection of some data, and frontend which displays one item of the collection.
At the backend I have ItemIndex -- whenever it changes, it fires up OnScroll event.
I also have AddNewItem method, it adds new item at the end of the collection. The end of the method is calling OnNewItem event handler.
And here is the catch -- in AddNewItem I have to change ItemIndex, which fires OnScroll. One of the receivers of both (!) OnScroll and OnNewItem if frontend which displays selected item.
In such case it is called twice (not good). One solution would be altering item_index instead of ItemIndex, and this way preventing OnScroll, but I don't like it because ItemIndex does not act as black box anymore.
Is there any established pattern for sequential firing events, and sending only "important" ones (here: OnNewItem overrides OnScroll)? My idea would be to define an event scope, then instead of sending events directly, just register them for sending, and at the close of scope sort them and send the required ones.
In general -- question -- how should I deal with potential sequential event triggering. Use internals to avoid sending redundant events? Ignore the overhead? ...?
The answer seems obvious to me athough I could have easily missed something:
private bool IsAdding { get; set; }
private int item_index;
private IList m_collection;
public void AddNewItem(object item)
{
if (item == null)
{
throw new Exception("Cannot add null item."); // little bit of contracting never hurts
}
m_collection.Add(item);
IsAdding = true;
ItemIndex = collection.Count - 1; //I'm just making assumptions about this piece but it is not important how you decide what your index is to answer the question
if (OnNewItem != null)
{
OnNewItem(this, EventArgs.Empty);
}
}
public int ItemIndex
{
get { return item_index =; }
set
{
item_index = value;
if (!IsAdding && OnScroll != null) //won't double fire event thanks to IsAdding
{
OnScroll(this, EventArgs.Empty);
}
IsAdding = false; //need to reset it
}
}
One thing I would note is that you made mention of just simply altering item_index directly but that wouldn't have a blackbox behavior. Well black box is all well and good ... but that term only applies to objects interacting with this class we have been discussing.
You should feel empowered to use the internals of your class within itself. It is not good OOP to blackbox items within itself. If you are doing that then your class probably has design issues where it should be split into multiple classes.
One solution is to use a 'latch' of some form. When updating, you perform your UI actions via a helper which sets a flag saying 'hey, I'm in a special state!'. Then, when raising events, you check to see if the latch is set -- if it is, you skip raising those events.
It's basically a very simple, generalised version of what Matthew posted. Depending on the situation, setting a flag may be more than adequate.
Jeremy Miller's explanation is worth reading
You could point both events at a single function. The function can determine the sender and perform the appropriate action(s).
Related
I have the following code and am wondering how to break it down? It works great but was written by a guru and is over my head. Thank you in advance for any help.
The code basically writes device information sent and received to the GUI. It seems like it has events created based on the device and also invokes GUI stuff.
Why would you need to invoke?
I guess I'm wondering if this is overly complicated or appropriate? What may be a better way to accomplish the same task?
I'm also wondering what the "delegate { };" does?
public event EventHandler CommunicationPerformed = delegate { };
SerialPort _port;
readonly int _delay = 100;
private string ReadAndUpdateStatus()
{
string read = _port.ReadExisting();
CommunicationPerformed?.Invoke(this, new LoaderReadWriteEventArgs(read, LoaderCommunicationDirection.Read));
return read;
}
private void WriteAndUpdateStatus(string data)
{
if (!data.StartsWith("//")) //ignore "Comment" lines but show them on the GUI to read
_port.Write(data);
CommunicationPerformed?.Invoke(this, new LoaderReadWriteEventArgs(data, LoaderCommunicationDirection.Write));
}
public class LoaderReadWriteEventArgs : EventArgs
{
public LoaderCommunicationDirection Direction { get; }
public string Value { get; }
public LoaderReadWriteEventArgs(string value, LoaderCommunicationDirection direction)
{
Value = value;
Direction = direction;
}
}
public enum LoaderCommunicationDirection
{
Read,
Write
}
You asked three questions, and as usual, only one of them got answered. Try to ask only one question in your question.
I'm also wondering what the delegate { } does?
public event EventHandler CommunicationPerformed = delegate { };
As the other answer notes, events are null by default in C#. This technique makes an event handler that does nothing, but is not null.
There are, unfortunately, many syntaxes for an anonymous function in C#. delegate {} means "give me a do-nothing function that matches any non-ref-out formal parameter list that is void returning". That's why people do delegate{}, because it works almost anywhere in a context where an event handler is expected.
I think you need to review this https://learn.microsoft.com/en-us/dotnet/standard/events/.
Why would you need to invoke?
To broadcast to event handlers (any party who registered for this event get notified this way)
I guess I'm wondering if this is overly complicated or appropriate?
*What may be a better way to accomplish the same task?
This is not complicated. This is pretty much as easy as it gets.*
I'm also wondering what the "delegate { };" does?
my two cents.
I dont know which code line you are refering but a delegate is a type that holds a reference to a method. A delegate is declared with a signature that shows the return type and parameters for the methods it references, and can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback. A delegate declaration is sufficient to define a delegate class.
orhtej2 answered your first question quite nicely. Using the explicit Invoke method allows you to leverage the null conditional operator, which reduces the code to fire the event a single line.
As for whether this is overly complicated: No, that's basically how events are done.
What I've sometimes seen (especially in combination with the INotifyPropertyChanged interface in MVVM patterns) are helper methods, which encapsulate the longer, but more obvious pre-C#6 code and let you fire the event with less plumbing.
private void FireCommPerformed(string value, LoaderCommunicationDirection direction)
{
EventHandler handler = CommunicationPerformed;
if (handler != null)
{
handler(this, new LoaderReadWriteEventArgs(value, direction)));
}
}
You could then use it like this:
private string ReadAndUpdateStatus()
{
string read = _port.ReadExisting();
FireCommPerformed(read, LoaderCommunicationDirection.Read);
return read;
}
The Delegate { } is simply an empty delegate, like a null for events. Unless some other method in the code subscribes to the CommunicationPerformed event of this class during runtime, nothing will happen when the event is fired.
Let's focus in on what is exactly happening here. This should help you figure out everything else.
CommunicationPerformed?.Invoke(this, new LoaderReadWriteEventArgs(read, LoaderCommunicationDirection.Read));
This is checking to see if the delegate (event handlers are delegates) (CommunicationPerformed) is null.
Delegates are pointers (but with extra functionality).
If the delegate (pointer) is null, it means that nothing has been assigned to it.
Pointers store memory locations. In this case, it makes a memory reference to the function 'this'. 'This' is a reference to ReadAndUpdateStatus().
So this line basically says: "since the pointer is null, have this pointer reference the ReadAndUpdateStatus() function".
But what about the event args? Well... This is where delegates diverge from pointers.
Delegates don't just safely hold and store memory locations. They also can hold parameters.
You use a class that extends from EventArgs as the way of passing in a list of parameters.
From here, the event handler (event handlers are delegates) CommunicationPerformed will coordinate sending that list of arguments to whatever functions require it.
These functions are called whenever CommunicationPerformed is invoked (e.g. told to run). This is typically indicated with a:
+=CommunicationPerformed(foo,bar)
Now - why would use event handlers (or any delegate - for that matter)?
They're verbose and annoying to read (way more work than writing a simple bool and a trigger function), they don't look like other function, and they're frankly weird - right?
Except that they're really useful. Here's how:
1.) They work a lot like Tasks. You can invoke them in Parallel, in loops, wherever. They keep consistent state. They don't "bleed" and cause bugs.
2.) They're pointers. Guaranteed pass-by-reference. Except, they're magical, and if you stop using the delegate, they won't linger in memory.
3.) They allow you to control state in loops. Sometimes, a bool trigger won't work properly if you're in a really tight loop. You fire an event? Guaranteed behavior that your trigger will only be fired once.
I'm gonna try to answer #1 and #2 (3 is already covered).
#1 - At some point, someone decided that other parts of the program could subscribe to an event that tells them when communication has been performed. Once that decision has been made, it's kind of a "contract". You perform the communication->you fire the event that notifies subscribers that communication has been performed. What those subscribers are doing about that, or why they need to know...Actually not really any of your concern if this class is your focus. In theory, at least. And often that's really practically the case. If your class is doing its job, it's not really your concern who is listening to the events.
#2 - I do think the method of declaring events and event handlers in your code is overly complicated. Plenty of people (and official Microsoft best practices) disagree with me. You can google "why should my event handlers use eventargs" and read plenty on the subject. Or Look here. Another approach is the following:
public event Action<string, LoaderCommunicationDirection> CommunicationPerformed;
void PerformWrite()
{
string myComm = "String I'm sending";
//Line of code that performs communication that writes string here
CommunicationPerformed?.Invoke(myComm, LoaderCommunicationDirection.Write);
}
This is much more succinct than having an entire class that derives from EventArgs. However, it has the very obvious drawback that if you are an event subscriber...you have no idea what string is. Of course, since it's named value in your code...that's not much more helpful. And a comment above the event declaration is just about as useful.
In WPF, I have a property with only a get{}. The value is coming from the return of method. NotifyPropertyChanged is often used within a property set{}. It can then notify the UI and the updated value is displayed. But with a get{} only, there isn't a way of detecting if a new or different value is available since you have to execute the method to check.
Is there some way to update the UI without having to keep a local value that contains the last value from the method, in which case a compare would need to be done?
But with a get{} only, there isn't a way of detecting if a new or different value is available since you have to execute the method to check.
The problem boils down to this: What is changing the property? The method that changes the property should call your NotifyPropertyChanged with the name of the property, which will, in turn, cause WPF to refetch the value and update the user interface.
WPF doesn't care where the PropertyChanged event gets raised - it just listens for it, and refreshes the binding as needed.
Edit in response to comment:
It sounds like this may be the result of performing some operation upon your Model class. In this case, it's common that you know that one or more properties may change, but not necessarily which ones. If your Model implements INotifyPropertyChanged, you can subscribe to that and "bubble up" the notifications to the UI via your NotifyPropertyChanged method. If it does not, however, there is another option.
If you know that one or more properties may change, you can raise a PropertyChanged event with string.Empty as the PropertyName in the EventArgs. This will cause all bound properties to get refreshed by WPF. This is likely just a matter of putting something like this in your code:
this.Model.DoSomething(); // This will change 1+ properties
this.NotifyPropertyChanged(string.Empty); // Refresh our entire UI
I wouldn't recommend doing this everywhere, however, as it does add overhead - but it's often the cleanest solution if you don't know which properties will change when you perform an operation.
Yes. Where you change the source data you would need to fire the INotify on the property. Here is an example.
private int _myvalue = 3;
public bool MyProperty
{
get { return IsAProperty(); }
}
public bool IsAProperty()
{
return _myvalue + 1 == 4;
}
public void SetValue(int value)
{
_myvalue = value;
NotifyPropertyChanged(MyProperty);
}
I have a situation where I have a couple of variables who's values depend on each other like this:
A is a function of B and C
B is a function of A and C
C is a function of A and B
Either value can change on the UI. I'm doing the calculation and change notification like this:
private string _valA;
private string _valB;
private string _valC;
public string ValA
{
get { return _valA; }
set
{
if (_valA != value)
{
_valA = value;
RecalculateValues("ValA"); //Here ValB and ValC are calculated
OnPropertyChanged("ValA");
}
}
}
public string ValB
{
get { return _valB; }
set
{
if (_valB != value)
{
_valB = value;
RecalculateValues("ValB"); //Here ValA and ValC are calculated
OnPropertyChanged("ValB");
}
}
}
(...)
private void RecalculateValues(string PropName)
{
if (PropName == "ValA")
{
_valB = TotalValue * _valA;
OnPropertyChanged("ValB");
_valC = something * _valA
OnPropertyChanged("ValC");
}
else
(...)
}
I'm calling the calculation method on the setter of the changed variable, calculating the values for _valB, _valC (for example) and then calling PropertyChanged for these ones.
I do it like this because of the dependencies between the variables, like this i can control which variable gets calculated with the correct values. I also thought about triggering the PropertyChanged for the other variables and perform the calculation on the getter of the variables but i would have to know which property changed before and use that value...not sure if it's the best/simplest solution.
Is this a good way to do this? I don't like the idea of performing this on the setter block, but at the time I can't see any better way to do it.do you see any other (better or cleaner solution)?
Another issue I have is using IdataErrorInfo for validation/presenting error info to the UI.The thing is the this[columnName] indexer gets called at the end of the setter and I needed to validate the values before the calculation, so that if the value inputted is not valid the calculation would not happen.I'm seriously considering abandoning IDataErrorInfo and simply calling my validation method before the calculation(s) occurs. Is there any way to explicitly calling it or right after the value attribution?
NOTE: ValidationRules are not an option because I need to call validation logic on another object from my ViewModel.
Its alright to call your Validation and Calculation in Setter, as long as it does not block the thread and goes into heavy cpu intensive calculations. If you have simple 5 to 10 math based statements without involving complex loops, its alright.
For databinding and WPF, this is the only way, However there is one more implementation called IEditableObject which has BeginEdit, CancelEdit and EndEdit, where you can do your calculation and validation on "EndEdit" function.
In BeginEdit, you can save your all values in temp storage, in CancelEdit you can bring back all values from temp and fire PropertyChaged event for all values those were modified and in EndEdit, you can finally update all variables and fire PropertyChanged for all those are updated.
IEditableObject will be best for performance wise, but it may not display new values until it was cancelled or ended, however to display instantly the only way to do is the way you are doing it.
In case of heavy cpu usage, you can invoke another thread to do calculation and set variables and at the end you can fire PropertyChanged, but yes technicaly you are just doing same thing while setting value in setter but asynchronously.
Since you can evoke NotifyPropertyChanged from anywhere in the class, one way to simplify this is to have your Calculate method fire the NotifyPropertyChanged for all three variables. I use this trick when I have complex calculations with multi-dependencies. Sometimes you'll still want to fire the event in the Setter: in that case I use a flag field to disable the event when I am updating the property from within the Calculations so that the event is not fired twice.
What purpose do protected or private (non-static) events in .NET really serve?
It seems like any private or protected event is more easily handled via a virtual method. I can (somewhat) see the need for this in static events, but not for normal events.
Have you had a use case before that clearly demonstrates a need or advantage for a non-static protected or private event?
Here's a slightly bizarre but real-world scenario I implemented once. You have machine-generated and user-generated halves of a partial class. The machine-generated half contains code which wishes to inform the user-generated half when some event occurs. But the user-generated half might not care to do anything, or it might care to do rather a lot. It seems rude of the machine-generated half to require that the user-generated half implement a particular method in order to handle a message they don't have any interest in listening to.
To solve this problem, the machine-generated half could fire on a private event. If the user-generated half cares, it can subscribe the event. If not, it can ignore it.
This scenario is now addressed more elegantly by partial methods in C# 3, but that was not an option back in the day.
Seems to me that a good example of where a private event is useful is in component/control building, often you may have a component that is a composite of 1 or more other components, private events that contained components can subscribe to is a handy and easy implementation of an observer pattern.
Edit:
Let me give an example...
Say you are writing a Grid type control, and inside of this control you would most likely have a bunch of contained classes that are created dynamically Rows, Cols, headers etc for example, say you want to notify these contained classes that something they care about has happend, say a Skinning change or something like that, something that you don't necesarrily want to expose as an event to the grid users, this is where private events are handy, simply have one or 2 handlers and as you create each instance of your row or col or whatever attach the handler, as otherwise you just have to write your own observer mechanism, not hard, but why when you dont have to and you can just use multicast events.
Nested types have access to the enclosing type's private and protected events. I've used this feature to notify child controls (the nested type) of state changes in the parent control (the enclosing type) in a Silverlight application.
Sorry to drag up an old thread, but I use private events with impunity in one of my projects, and personally, I find it's a good way of solving a design issue:
Here's the abbreviated code:
public class MyClass
{
private event EventHandler _myEvent;
public ExternalObject { get; set; }
public event EventHandler MyEvent
{
add
{
if (_myEvent.GetInvocationList().Length == 0 && value != null)
ExternalObject.ExternalEvent += HandleEvent;
_myEvent+= value;
}
remove
{
_myEvent-= value;
if (_myEvent.GetInvocationList().Length == 0)
ExternalObject.ExternalEvent -= HandleEvent;
}
}
private void HandleEvent(object sender, EventArgs e)
{
_myEvent.Raise(this, EventArgs.Empty); // raises the event.
}
}
Basically, MyEvent is only ever raised in the event handler of ExternalObject.ExternalEvent, so if there's no handlers for MyEvent then I don't need to attach a handler to the external event, speeding up the code slightly by saving a stack frame.
Not only the current instance can access a private member. Other instances of the same type can too! This enables some scenarios where this access control may be useful.
I am thinking of a tree structure where all nodes inherit a certain type and a private/protected event allows to propagate leaf events to their parents. Since they are the same type, the parent can register to the child's private event. Yet any client of the tree structure cannot.
I can definitely see a use case in a directory like storage system where where each directory needs to propagate its last modified date to its parent for example.
In C# what is the advantage of
public class blah
{
public event EventHandler Blahevent;
}
versus
public class blah
{
private event EventHandler blahevent;
public event EventHandler Blahevent
{
add
{
blahevent+=value;
}
remove
{
blahevent-=value
}
}
}
or vice versa.
does the first one open you up to blahinstance.Blahevent = null, or blahinstance.Blahevent(obj,even)
There is no advantage to explicit implementation of the add/remove methods unless you want to do something different. Possible reasons:
Perhaps take control of the event backing code yourself (to directly link to some other event rather than going though a pointless cascade for example)
do something else in addition on add or remove
Change security demands on the add or remove
expose the underlying delegate
What the default implementation does is maintain a private hidden delegate field which is replaced each time a delegate is added or removed. For most cases there is no need to do any of the above but the flexibility is there.
The second one has the option of controlling exactly what happens when the specified event is subscribed to or unsubscribed from if there is specific logic that needs to run in addition to adding or removing the pointer.
You can exclude the delegate from serialization by using the [field: NonSerialized()] attribute on the private field.
You can place a breakpoint on the latter for debugging purposes. Sometimes this can be really useful (although after debugging I switch it back to the former).