singleton - Is this a valid use of the lock keyword in C#? -


I have a singleton class app settings Aspiknet app, where to check me value and optionally update Have to do. I know that I need to use the locking mechanism to stop multi-threading issues, but can someone verify that the following is a valid approach?

  private static void validate Validation () (if (AppSetting.Instance .EncryptionKey.Equals (Constants.ENCRYPTION_KEY, string Comprijnkordinl)) {lock (Aepaseting. Instrens) {if (app Setinging Kinstens. Ankripshnkiakwaljh (Sthirank.ansiarseepitian_ke, string Compiriynkordinl)) {Aepasetingkinstens. Ankripshnki = generate New Ankripshnki (); AppSetting.Instance.Save ();}}}}  

I have also seen examples where you are present Do not lock in any private sector should protect, but I think that the above approach is more intuitive.

Thank you!

The

the intuitive knowledge may be rich, but those instances the piece of code in the private sector to ensure that the lock is no other app can lock in such a lock that There is an application in the form of deadlock, which is always a good defensive practice.

If this is a small application and you are the only programmer working on it, you might be able to participate with locking on a public area / property (which I anticipate app setting. Is Instance?), But in any other situation, I strongly recommend that you go on the private field route. In the future when someone else, or in the future may have forgotten the details of the implementation of the bit, then in the future you will ensure completely locked down to save debugging time, app settings Take it. Somewhere far away in the code and everything crashes.

I also suggest that if you lose the most, locking is not free, but it is very quick to compare the string, especially since the second time in the lock It needs to be done.

Then, something like this:

  Private Object _instanceLock = New Object (); Private static zero valid encryption () {lock (appatting.instance._ instanceLock) {if (AppSetting.Instance.EncryptionKey.Equals (Constants.ENCRYPTION_KEY, StringComparison.Ordinal)) {AppSetting.Instance.EncryptionKey = GenerateNewEncryptionKey (); AppSetting.Instance.Save (); }}}  

What are your requirements for keeping the compatibility with the rest of the state in episode, besides an additional refinement. Instance will have to use a different private lock object instead of encryption and any associated fields, each time locking the whole instance.


Comments

Popular posts from this blog

Eclipse CDT variable colors in editor -

AJAX doesn't send POST query -

wpf - Custom Message Box Advice -