An order pushes the magic of ObservableCollection.
Recently, a seller app in taobao needs to subscribe to taobao order push. The sample code is as follows:
I. first look at the gameplay
First, I perform the Add and Remove operations on the set, and register a change event for him. Then, I use a working thread to execute the logic of the change event to see what feedback I have given, the magical effect begins immediately.
Class Program {static void Main (string [] args) {ObservableCollection <string> list = new ObservableCollection <string> () {"1"}; list. collectionChanged + = list_CollectionChanged; for (int I = 0; I <1000; I ++) {if (I % 3 = 1) {list. removeAt (0);} else {list. add (I. toString () ;}} Console. writeLine ("all ends !!! "); Console. read ();} static void list_CollectionChanged (object sender, yycollectionchangedeventargs e) {// in order not to prevent the main thread from adding, the event uses the "working thread" to process the Task. factory. startNew (o) => {var obj = o as yycollectionchangedeventargs; switch (obj. action) {case policycollectionchangedaction. add: Console. writeLine ("current Thread: {0}, Operation: {1} data: {2}", Thread. currentThread. managedThreadId, obj. action. toString (), obj. newItems [0]); break; case when ycollectionchangedaction. move: break; case when ycollectionchangedaction. remove: Console. writeLine ("current Thread: {0}, Operation: {1} data: {2}", Thread. currentThread. managedThreadId, obj. action. toString (), obj. oldItems [0]); break; case when ycollectionchangedaction. replace: break; case when ycollectionchangedaction. reset: break; default: break;} Thread. sleep (1000) ;}, e );}}
From the perspective of appearance, CollectionChanged has completely monitored all actions of the Set, including Add and Remove. Obviously, this is much better than the data for my round training. If it is used, everyone will use it,
The key is to see how it is implemented. Next we will analyze it.
Ii. Simple Analysis of source code
First, we will find that the ObservableCollection inherits a Collection and implements two interfaces INotifyCollectionChanged: "Property notification" and "Collection notification,
INotifyPropertyChanged ).
Then we found that the Add method is provided by the parent class, and then the InsertItem method provided in the ObservableCollection is called, as shown in.
We can see that in the Add method on the upper layer, the InsertItem method is actually called, and at last we can see that the OnCollectionChanged core method is not very happy ....
Let's take a look at it with me.
Finally, we were happy to see the trigger mechanism of this class, but we made an event trigger method at the end of the Add/Remove method. At the same time, we also saw that, this is a synchronization operation, which means,
By default, my CollectionChanged logic will block the Add operation on the upper layer, which requires special attention.