1: /// <summary>
2: /// Helper class for dispatcher operations on the UI thread.
3: /// </summary>
4: public static class DispatcherHelper
5: {
6: /// <summary>
7: /// Gets a reference to the UI thread's dispatcher, after the <see cref="Initialize()"/>
8: /// method has been called on the UI thread.
9: /// </summary>
10: public static Dispatcher UIDispatcher { get; private set; }
11: /// <summary>
12: /// Executes an action on the UI thread. If this method is called from the UI
13: /// thread, the action is executed immendiately. If the method is called from
14: /// another thread, the action will be enqueued on the UI thread's dispatcher
15: /// and executed asynchronously.
16: /// For additional operations on the UI thread, you can get a reference to the
17: /// UI thread's dispatcher thanks to the property <see cref="UIDispatcher"/>
18: /// </summary>
19: /// <param name="action">The action that will be executed on the UI thread.</param>
20: public static void CheckBeginInvokeOnUI(Action action)
21: {
22: if (UIDispatcher == null || UIDispatcher.CheckAccess())
23: {
24: action();
25: }
26: else
27: {
28: UIDispatcher.BeginInvoke(action);
29: }
30: }
31: public static void CheckBeginInvokeOnUI<T>(Action<T> action, T arg)
32: {
33: if (UIDispatcher == null || UIDispatcher.CheckAccess())
34: {
35: action(arg);
36: }
37: else
38: {
39: UIDispatcher.BeginInvoke(action, arg);
40: }
41: }
42: /// <summary>
43: /// This method should be called once on the UI thread to ensure that the <see cref="UIDispatcher"/>
44: /// property is initialized.
45: /// In a Silverlight application, call this method in the Application_Startup
46: /// event handler, after the MainPage is constructed.
47: /// In WPF, call this method on the static App() constructor.
48: /// </summary>
49: public static void Initialize()
50: {
51: UIDispatcher = Dispatcher.CurrentDispatcher;
52: }
53: }
No comments:
Post a Comment