From ecf92647d46de832a544b59464debd0c74026ce2 Mon Sep 17 00:00:00 2001 From: Hecate2 <2474101468@qq.com> Date: Tue, 20 Dec 2022 10:23:34 +0800 Subject: [PATCH] await transaction efficiently with semaphore --- Fairy.Engine.cs | 2 +- Fairy.Utils.cs | 16 +++++----------- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/Fairy.Engine.cs b/Fairy.Engine.cs index 113bcf4..48ee29c 100644 --- a/Fairy.Engine.cs +++ b/Fairy.Engine.cs @@ -296,7 +296,7 @@ internal void InitializeTimer() timer = new(OnTimer, null, settings.SessionExpirationTime.Milliseconds, 60000); } - internal void OnTimer(object state) + internal void OnTimer(object? state) { List<(string Id, FairySession Session)> toBeDestroyed = new(); foreach (var (id, session) in sessionStringToFairySession) diff --git a/Fairy.Utils.cs b/Fairy.Utils.cs index e64be64..ff47b03 100644 --- a/Fairy.Utils.cs +++ b/Fairy.Utils.cs @@ -83,19 +83,13 @@ protected virtual JToken AwaitConfirmedTransaction(JArray _params) { return json; } - uint count = 1; - bool expectBlockIn15Secs = false; - CommittedHandler getConfirmedTransactionAfterCommitted = delegate(NeoSystem @system, Block @block){ count += 1; expectBlockIn15Secs = true; json = GetConfirmedTransaction(hash, verbose); }; + SemaphoreSlim signal = new SemaphoreSlim(0, 1); + uint count = 0; + CommittedHandler getConfirmedTransactionAfterCommitted = delegate(NeoSystem @system, Block @block){ json = GetConfirmedTransaction(hash, verbose); count += 1; signal.Release(); }; Blockchain.Committed += getConfirmedTransactionAfterCommitted; - while (count <= waitBlockCount) + while (count < waitBlockCount) { - if (expectBlockIn15Secs == false) - Thread.Sleep(500); - else - { - expectBlockIn15Secs = false; - Thread.Sleep(14500); - } + signal.Wait(); if (json != null) { Blockchain.Committed -= getConfirmedTransactionAfterCommitted;