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); + } + } + } +}