From 7380cdfdc24cb497d4f50c1d05176fecbc3a1796 Mon Sep 17 00:00:00 2001 From: oneRain Date: Tue, 28 Apr 2020 17:03:50 +0800 Subject: [PATCH] =?UTF-8?q?chore:=20=E8=B0=83=E6=95=B4=E5=91=BD=E5=90=8D?= =?UTF-8?q?=E7=A9=BA=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Common/Log/LCLogLevel.cs | 2 +- Common/Log/LCLogger.cs | 2 +- .../SingleThreadSynchronizationContext.cs | 43 +++++++++++++++++++ 3 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 Common/Task/SingleThreadSynchronizationContext.cs diff --git a/Common/Log/LCLogLevel.cs b/Common/Log/LCLogLevel.cs index fefcd9d..f43aaf5 100644 --- a/Common/Log/LCLogLevel.cs +++ b/Common/Log/LCLogLevel.cs @@ -1,4 +1,4 @@ -namespace LeanCloud.Common { +namespace LeanCloud { /// /// 日志级别 /// diff --git a/Common/Log/LCLogger.cs b/Common/Log/LCLogger.cs index d54ec23..1ffbcac 100644 --- a/Common/Log/LCLogger.cs +++ b/Common/Log/LCLogger.cs @@ -1,7 +1,7 @@ using System; using System.Text; -namespace LeanCloud.Common { +namespace LeanCloud { /// /// 日志类 /// diff --git a/Common/Task/SingleThreadSynchronizationContext.cs b/Common/Task/SingleThreadSynchronizationContext.cs new file mode 100644 index 0000000..cd08e62 --- /dev/null +++ b/Common/Task/SingleThreadSynchronizationContext.cs @@ -0,0 +1,43 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Concurrent; +using System.Collections.Generic; + +namespace LeanCloud.Common { + /// + /// 单线程环境,用于控制台应用 await 返回 + /// + public class SingleThreadSynchronizationContext : SynchronizationContext { + private readonly BlockingCollection> queue = new BlockingCollection>(); + + public override void Post(SendOrPostCallback d, object state) { + queue.Add(new KeyValuePair(d, state)); + } + + public void RunOnCurrentThread() { + while (queue.TryTake(out KeyValuePair workItem, Timeout.Infinite)) { + workItem.Key(workItem.Value); + } + } + + public void Complete() { + queue.CompleteAdding(); + } + + public static void Run(Func func) { + SynchronizationContext prevContext = Current; + try { + SingleThreadSynchronizationContext syncContext = new SingleThreadSynchronizationContext(); + SetSynchronizationContext(syncContext); + + Task t = func(); + syncContext.RunOnCurrentThread(); + + t.GetAwaiter().GetResult(); + } finally { + SetSynchronizationContext(prevContext); + } + } + } +}