This article is a mirror article of machine translation, please click here to jump to the original article.

View: 19792|Reply: 0

[Source] Usage of SyncRoot in StringDictionary

[Copy link]
Posted on 11/23/2016 2:26:38 PM | | | |

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




Previous:How to use WPF Trigger to switch buttons
Next:c# Use OCR to recognize Chinese images
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com