I am using Semaphore to limit the number of concurrent instances my application can run.
There are many ways a process can terminate. Can the Semaphore be created so it automatically releases upon process exit?
EDIT:
I would like some magic to automatically clean up the semaphore ‘raised’ state for the process owning it upon exit or crash. Just to be sure that it is cleared, no matter what.
MORE:
I am looking for any viable option for it, considering:
- it would be great that NO external application is required to get a hold on every instance of the protected application
- it doesn’t have to be Semaphore – any synchronization object that has COUNTER and is AUTOMATICALLY released upon death of a owner process will be fine, even if it’s cheating
- I am using .NET 2.0, can’t move to newer version on this project, but can use c/c++ and inter-op to leverage something if there is something
You can hook into the
AppDomain.ProcessExitevent to perform any cleanup operations like releasing the semaphore.Generally, named semaphores are designed to coordinate resources across processes without taking particular process life-time into account. Semaphores in .NET are backed by native Windows semaphore objects, and the MSDN says:
Hence the right approach is explicit handling before process termination.
Update — Other options to consider:
AppDomain.ProcessExitevent, consider creating anIDisposablewrapper that would acquire the semaphore in its constructor and release it in theDisposemethod.Update — In case of an application crash or forced termination (i.e. via Task Manager)
ProcessExitwon’t have a chance to be handled. Hence any unmanaged resources shared between multiple processes may not be finalized / disposed / handled correctly. See this article for further details.A viable option may be creating a named pipe. The advantage of named pipes is they cease to exit once the creating process is terminated. According to MSDN:
There are two options to limit the number of pipe instances:
FILE_FLAG_FIRST_PIPE_INSTANCEflag in thedwOpenModeargument it is possible to prohibit creation of multiple instances of the pipe. Then, the second process attempting to create the pipe will receive an error.nMaxInstancesargument. WhenNare allowed, theN+1st process will receive an error.