SingleInstanceGuard.cs 711 B

123456789101112131415161718192021222324252627282930313233
  1. using System;
  2. using System.Threading;
  3. namespace BeiJingComService.Infrastructure
  4. {
  5. public sealed class SingleInstanceGuard : IDisposable
  6. {
  7. private readonly Mutex _mutex;
  8. private bool _owned;
  9. public SingleInstanceGuard(string mutexName)
  10. {
  11. _mutex = new Mutex(true, mutexName, out _owned);
  12. }
  13. public bool IsOwned
  14. {
  15. get { return _owned; }
  16. }
  17. public void Dispose()
  18. {
  19. if (_owned)
  20. {
  21. try { _mutex.ReleaseMutex(); }
  22. catch { }
  23. _owned = false;
  24. }
  25. try { _mutex.Dispose(); }
  26. catch { }
  27. }
  28. }
  29. }