andrew4582

WPF Dispatcher Extentions

Oct 30th, 2014
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.62 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3. using System.Windows.Threading;
  4.  
  5. namespace Client.AppUtils
  6. {
  7.     /// <summary>
  8.     /// Extentions class for Dispatcher
  9.     /// </summary>
  10.     public static class DispatcherExtentions
  11.     {
  12.         /// <summary>
  13.         /// Returns true if the caller is on a separate thread than the UI thread
  14.         /// </summary>
  15.         public static bool IsInvokeRequired(this Dispatcher dispatcher)
  16.         {
  17.             return dispatcher.Thread.ManagedThreadId != Thread.CurrentThread.ManagedThreadId;
  18.         }
  19.  
  20.         /// <summary>
  21.         /// Calls the Dispatcher.Invoke() method if the caller is on a separate thread than the UI thread, otherwise the provided method is called
  22.         /// </summary>
  23.         public static void InvokeIfNeeded(this Dispatcher dispatcher, Action method, params object[] args)
  24.         {
  25.             if (IsInvokeRequired(dispatcher))
  26.                 dispatcher.Invoke(method, args);
  27.             else
  28.                 method();
  29.         }
  30.  
  31.         /// <summary>
  32.         /// Calls the Dispatcher.Invoke() method if the caller is on a separate thread than the UI thread, otherwise the provided method is called
  33.         /// </summary>
  34.         public static T InvokeIfNeeded<T>(this Dispatcher dispatcher, Func<T> method)
  35.         {
  36.             if (IsInvokeRequired(dispatcher))
  37.                 return dispatcher.Invoke<T>(method);
  38.             else
  39.                 return method();
  40.         }
  41.  
  42.         /// <summary>
  43.         /// Calls the Dispatcher.BeginInvoke() method if the caller is on a separate thread than the UI thread, otherwise the provided method is called
  44.         /// </summary>
  45.         public static void BeginInvokeIfNeeded(this Dispatcher dispatcher, Action action)
  46.         {
  47.             if (IsInvokeRequired(dispatcher))
  48.                 dispatcher.BeginInvoke(action);
  49.             else
  50.                 action();
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment