Automatic release of Semaphore by process Exit

I use Semaphore to limit the number of simultaneous instances that my application can run.

There are many ways to stop the process. Is it possible to create Semaphoreso that it automatically frees up when the process ends?

EDIT:

I would like some kind of magic to automatically clear the state with a raised semaphore for the process that it owned when it exited or failed. Just to be sure that it is cleansed no matter what.

MORE:

I am looking for a viable option for you, given:

  • It would be great that no external application is required for external access to any instance of a secure application.
  • it should not be a semaphore - any synchronization object that has a COUNTER and is AUTOMATICALLY released after the death of the process owner will be fine, even if it cheats
  • I am using .NET 2.0, I can’t switch to a newer version of this project, but I can use c / C ++ and inter-op to use something if there is something
+3
source share
3 answers

You can connect to an event AppDomain.ProcessExitto perform any cleanup operations, such as freeing up a semaphore.

Typically, these semaphores are designed to coordinate resources between processes without taking into account the specific life of the process. Semaphores in .NET are supported by native Windows semaphore objects , and MSDN says:

, . ; ReleaseSemaphore .

, - .


. :

  • "" AppDomain.ProcessExit, IDisposable, Dispose.
  • : ? () ?

. (.. ) ProcessExit . , , , // . . .

. , . MSDN:

, . , .

:

  • : FILE_FLAG_FIRST_PIPE_INSTANCE dwOpenMode, . , , .
  • : nMaxInstances. N , N+1 st .
+4

- " " , . ProcessExit , - , trappable (StackOverflowException InvalidProgramException .)

@http://msdn.microsoft.com/en-us/library/system.runtime.constrainedexecution.criticalfinalizerobject.aspx, " (CLR) , ​​ , CER, , CLR ."

+4

, , .Net 3.5 a NamedPipeServerStream .

  NamedPipeServerStream pipe;
  try
  {
    pipe = new NamedPipeServerStream(name, PipeDirection.InOut, 3);
  }
  catch (IOException)
  {
    //Maximum number of instances reached (3).
  }

I advise you to keep a static link on the pipe to avoid termination until you exit the process. The downside of the pipe is that you cannot wait until the instance is available without interrogation.

+1
source

All Articles