C# object-oriented programming, provides a lot of user-friendly operation classes, now this StringDictionary is a collection of classes that specialize in storing strings as keys and values, the meaning of this class is: C# knows that string in the value type is quite widely used, other value types can also be converted into corresponding string types, this is the meaning of this collection, but you can still use other collection objects to replace it, but pay attention to one point, If it is string storage, this can reduce memory loss and reduce the time it takes to run the program
SyncRoot can be used to synchronize access to the StringDictionary
To put it bluntly, it is the concept of lock, let's write a program to test it:
The code is as follows:
We have two threads at the same time to add data to the StringDictionary dictionary,
The execution time difference between the first thread and the second thread is one second, in order to widen the time difference and prevent execution from being too fast.
You can see that the threads have gone to the two methods, and when adding the second piece of data, they have been waiting for the first data to be added before adding the second data, and the addition time is very fast.
Below, we will write it in a different way to make it easier to understand:
3 threads are opened, and the data is added, and the 3 threads are executed almost at the same time, but when the data is added, each is 10 seconds apart.
In summary, when multi-threaded access, we can use SyncRoot to ensure thread security
|