[Mac]] Add NSApplication.IsUIThread property
authorthefiddler <stapostol@gmail.com>
Wed, 23 Jul 2014 19:14:47 +0000 (21:14 +0200)
committerthefiddler <stapostol@gmail.com>
Wed, 23 Jul 2014 19:14:47 +0000 (21:14 +0200)
This can be used to check whether it is safe to access UI components in
the calling thread.

Source/OpenTK/Platform/MacOS/Cocoa/NSApplication.cs

index 22295b0..bdab021 100644 (file)
@@ -29,7 +29,9 @@
 
 using System;
 using System.ComponentModel;
+using System.Diagnostics;
 using System.Runtime.InteropServices;
+using System.Threading;
 using OpenTK.Platform.MacOS;
 
 namespace OpenTK.Platform.MacOS
@@ -41,6 +43,9 @@ namespace OpenTK.Platform.MacOS
 
         static readonly IntPtr selQuit = Selector.Get("quit");
 
+        static readonly int ThreadId =
+            System.Threading.Thread.CurrentThread.ManagedThreadId;
+
         internal static void Initialize() { }
 
         static NSApplication()
@@ -103,9 +108,26 @@ namespace OpenTK.Platform.MacOS
             Cocoa.SendVoid(settings, Selector.Release);
         }
 
+        internal static bool IsUIThread
+        {
+            get
+            {
+                int thread_id = Thread.CurrentThread.ManagedThreadId;
+                bool is_ui_thread = thread_id == NSApplication.ThreadId;
+                if (!is_ui_thread)
+                {
+                    Debug.Print("[Warning] UI resources must be disposed in the UI thread #{0}, not #{1}.",
+                        NSApplication.ThreadId, thread_id);
+                }
+                return is_ui_thread;
+            }
+        }
+
         internal static event EventHandler<CancelEventArgs> Quit = delegate { };
 
+        [UnmanagedFunctionPointer(CallingConvention.Winapi)]
         delegate void OnQuitDelegate(IntPtr self, IntPtr cmd);
+
         static OnQuitDelegate OnQuitHandler = OnQuit;
         static void OnQuit(IntPtr self, IntPtr cmd)
         {