From ef6a55b3859155356e026634af52796d2e549589 Mon Sep 17 00:00:00 2001 From: Timerix Date: Mon, 13 Sep 2021 17:03:59 +0300 Subject: [PATCH] new mutex wrapper wiht autorelease --- SafeMutex.cs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 SafeMutex.cs diff --git a/SafeMutex.cs b/SafeMutex.cs new file mode 100644 index 0000000..1d7ca00 --- /dev/null +++ b/SafeMutex.cs @@ -0,0 +1,29 @@ +using System; +using System.Threading; + +namespace DTLib +{ + public class SafeMutex + { + readonly Mutex Mutex = new(); + bool isReleased = false; + + // тут выполняется отправленный код + public void Execute(Action action, out Exception exception) + { + try + { + exception = null; + Mutex.WaitOne(); + action(); + Mutex.ReleaseMutex(); + isReleased = true; + } + catch (Exception ex) + { + exception = ex; + if (!isReleased) Mutex.ReleaseMutex(); + } + } + } +}