From c71d2b8356cbe750ef945224311b16ae305876fa Mon Sep 17 00:00:00 2001 From: Timerix Date: Mon, 4 Oct 2021 22:31:14 +0300 Subject: [PATCH] reactivity --- Reactive/ReactiveProvider.cs | 2 +- Reactive/ReactiveStream.cs | 14 +++++--------- SafeMutex.cs | 19 +++++++++++++------ 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/Reactive/ReactiveProvider.cs b/Reactive/ReactiveProvider.cs index 84f91d4..3d487a0 100644 --- a/Reactive/ReactiveProvider.cs +++ b/Reactive/ReactiveProvider.cs @@ -13,7 +13,7 @@ namespace DTLib.Reactive event Action AnnounceEvent; public void Announce(T e) { - ReactiveWorkerMutex.Execute(()=>AnnounceEvent.Invoke(e)); + ReactiveWorkerMutex.Execute(() => AnnounceEvent.Invoke(e)); } public override void Join(ReactiveStream stream) diff --git a/Reactive/ReactiveStream.cs b/Reactive/ReactiveStream.cs index 819e47a..ed97520 100644 --- a/Reactive/ReactiveStream.cs +++ b/Reactive/ReactiveStream.cs @@ -7,23 +7,19 @@ namespace DTLib.Reactive { List Storage = new(); public event EventHandlerAsync ElementAdded; - bool StoreData = false; - SafeMutex StorageMutex = new(); + public int Length { get { return StorageMutex.Execute(() => Storage.Count); } } public ReactiveStream() { } - public ReactiveStream(bool storeData) => StoreData = storeData; public void Add(T elem) { - if (StoreData) StorageMutex.Execute(() => Storage.Add(elem)); + StorageMutex.Execute(() => Storage.Add(elem)); ElementAdded?.Invoke(this, elem); } - public void Clear() - { - if (StoreData) StorageMutex.Execute(() => Storage.Clear()); - else throw new Exception("Can't clear ReactiveStream because StoreData==false"); - } + public void Get(int index) => StorageMutex.Execute(() => Storage[index]); + + public void Clear() => StorageMutex.Execute(() => Storage.Clear()); } } diff --git a/SafeMutex.cs b/SafeMutex.cs index f7daa20..5eaa2ae 100644 --- a/SafeMutex.cs +++ b/SafeMutex.cs @@ -14,10 +14,7 @@ namespace DTLib try { exception = null; - Mutex.WaitOne(); - action(); - Mutex.ReleaseMutex(); - isReleased = true; + Execute(action); } catch (Exception ex) { @@ -28,8 +25,18 @@ namespace DTLib public void Execute(Action action) { - Execute(action, out Exception exception); - exception?.Throw(); + Mutex.WaitOne(); + action(); + Mutex.ReleaseMutex(); + isReleased = true; + } + public T Execute(Func action) + { + Mutex.WaitOne(); + var rezult = action(); + Mutex.ReleaseMutex(); + isReleased = true; + return rezult; } } }