Add NUIContext
authorMarcin Romaniuk <m.romaniuk@samsung.com>
Mon, 31 May 2021 23:17:11 +0000 (01:17 +0200)
committerPiotr Czaja <p.czaja@samsung.com>
Tue, 14 Sep 2021 11:01:34 +0000 (13:01 +0200)
NUIContext captures SynchronizationContext and allows to call main thread from other threads.

Fitness/FitnessApp.cs
Fitness/NUIContext.cs [new file with mode: 0644]

index 6e3d020e1999dbf6380493a8ad9c88467f8d6635..36fb80b0e2d07d23e8bed09dca211f0f188bcf1c 100644 (file)
@@ -24,6 +24,8 @@ namespace Fitness
         {
             base.OnCreate();
             Initialize();
+
+            NUIContext.Initialize();
         }
     }
 }
diff --git a/Fitness/NUIContext.cs b/Fitness/NUIContext.cs
new file mode 100644 (file)
index 0000000..ef62f39
--- /dev/null
@@ -0,0 +1,35 @@
+using System.Threading;
+
+namespace Fitness
+{
+    /// <summary>
+    /// NUIContext captures SynchronizationContext.
+    /// </summary>
+    public static class NUIContext
+    {
+        private static SynchronizationContext context;
+
+        /// <summary>
+        /// Save SychronizationContext.
+        /// </summary>
+        /// <remarks>
+        /// Must be called from the main thread.
+        /// </remarks>
+        public static void Initialize()
+        {
+            context = SynchronizationContext.Current;
+
+            Services.Logger.Debug($"capturing SynchronizationContext: {context}");
+        }
+
+        /// <summary>
+        /// Invoke Action within captured SynchronizationContext.
+        /// </summary>
+        /// <param name="action">Action to be called on the main thread.</param>
+        public static void InvokeOnMainThread(System.Action action)
+        {
+            SendOrPostCallback callback = _ => action?.Invoke();
+            context?.Post(callback, null);
+        }
+    }
+}