I'm writing an app that needs to write registry values inside of a key in a particular order, and other applications could be writing to the same key, at the same time.
Is there a way to temporarily lock a registry key for writes, to avoid multiple processes writing to this registry key at the same time, and the values getting messed up / out of order?
e.g. I need to write to HKCU\Software\Company\Product\ which already contains the values below:
Start1 = "abc"Start2 = "def"Start3 = "ghi"Because the last one is Start3, I need to create Start4.
The problem is if another process is running at the same time, detects that Start3 is the last one, and overrides my Start4 that I just created (because it didn't see it due to concurrency).
What would be a good way to prevent that from happening?
I don't have control over which (or how many) applications are writing to this key, and as such I can't tell them to pause or anything like that...
I'm looking for something like the pseudo-code below:
Registry.Lock("HKCU\Software\Company\Product\");
Registry.Write("Start4", "jkl");
Registry.Unlock("HKCU\Software\Company\Product\");
It looks like I'm going to answer my own question unfortunately.
Writing and Deleting Registry Data
It is not possible to lock a registry key during a write operation to synchronize access to the data. However, you can control access to a registry key using security attributes. For more information, see Registry Key Security and Access Rights.
More than one registry operation can be performed within a single transaction. To associate a registry key with a transaction, an application can use the RegCreateKeyTransacted or RegOpenKeyTransacted function. For more information about transactions, see Kernel Transaction Manager.
From: https://learn.microsoft.com/en-us/windows/win32/sysinfo/writing-and-deleting-registry-data
You have to use proper synchronization using the Mutex functions. Registry API, as most Windows API, is not threadsafe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With