25

我遇到了一个无效的跨线程访问问题,但进行了一些研究,我设法通过使用 Dispatcher 解决了它。

现在在我的应用程序中,我有延迟加载的对象。我会使用 WCF 进行异步调用,并且像往常一样使用 Dispatcher 来更新我的对象 DataContext,但是它不适用于这种情况。不过,我确实在这里找到了解决方案。这是我不明白的。

在我的 UserControl 中,我有代码可以在我的对象上调用Toggle方法。对此方法的调用是在这样的 Dispatcher 中进行的。

Dispatcher.BeginInvoke( () => _CurrentPin.ToggleInfoPanel() );

正如我之前提到的,这不足以满足 Silverlight。我不得不在我的对象中进行另一个Dispatcher 调用。我的对象不是 UIElement,而是一个处理所有自己的加载/保存的简单类。

所以问题是通过调用解决的

Deployment.Current.Dispatcher.BeginInvoke( () => dataContext.Detail = detail );

在我的课堂上。

为什么我必须调用 Dispatcher 两次才能实现这一点?一个高层的电话难道还不够吗?UIElement 中的Deployment.Current.Dispatcher和 Dispatcher之间有区别吗?

4

2 回答 2

21

理想情况下,存储一个Dispatcher您可以在其他地方使用的实例,而无需对其进行线程检查。

调用任何单例 .Current 实例实际上可能会导致调用跨线程访问检查。通过首先存储它,您可以避免这种情况以实际获取共享实例。

我使用“SmartDispatcher”,它在线程外调用时使用调度程序,否则只调用。它解决了这类问题。

帖子: http: //www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/

代码:

// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System.ComponentModel;

namespace System.Windows.Threading
{
    /// <summary>
    /// A smart dispatcher system for routing actions to the user interface
    /// thread.
    /// </summary>
    public static class SmartDispatcher
    {
        /// <summary>
        /// A single Dispatcher instance to marshall actions to the user
        /// interface thread.
        /// </summary>
        private static Dispatcher _instance;

        /// <summary>
        /// Backing field for a value indicating whether this is a design-time
        /// environment.
        /// </summary>
        private static bool? _designer;

        /// <summary>
        /// Requires an instance and attempts to find a Dispatcher if one has
        /// not yet been set.
        /// </summary>
        private static void RequireInstance()
        {
            if (_designer == null)
            {
                _designer = DesignerProperties.IsInDesignTool;
            }

            // Design-time is more of a no-op, won't be able to resolve the
            // dispatcher if it isn't already set in these situations.
            if (_designer == true)
            {
                return;
            }

            // Attempt to use the RootVisual of the plugin to retrieve a
            // dispatcher instance. This call will only succeed if the current
            // thread is the UI thread.
            try
            {
                _instance = Application.Current.RootVisual.Dispatcher;
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("The first time SmartDispatcher is used must be from a user interface thread. Consider having the application call Initialize, with or without an instance.", e);
            }

            if (_instance == null)
            {
                throw new InvalidOperationException("Unable to find a suitable Dispatcher instance.");
            }
        }

        /// <summary>
        /// Initializes the SmartDispatcher system, attempting to use the
        /// RootVisual of the plugin to retrieve a Dispatcher instance.
        /// </summary>
        public static void Initialize()
        {
            if (_instance == null)
            {
                RequireInstance();
            }
        }

        /// <summary>
        /// Initializes the SmartDispatcher system with the dispatcher
        /// instance.
        /// </summary>
        /// <param name="dispatcher">The dispatcher instance.</param>
        public static void Initialize(Dispatcher dispatcher)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher");
            }

            _instance = dispatcher;

            if (_designer == null)
            {
                _designer = DesignerProperties.IsInDesignTool;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static bool CheckAccess()
        {
            if (_instance == null)
            {
                RequireInstance();
            }

            return _instance.CheckAccess();
        }

        /// <summary>
        /// Executes the specified delegate asynchronously on the user interface
        /// thread. If the current thread is the user interface thread, the
        /// dispatcher if not used and the operation happens immediately.
        /// </summary>
        /// <param name="a">A delegate to a method that takes no arguments and 
        /// does not return a value, which is either pushed onto the Dispatcher 
        /// event queue or immediately run, depending on the current thread.</param>
        public static void BeginInvoke(Action a)
        {
            if (_instance == null)
            {
                RequireInstance();
            }

            // If the current thread is the user interface thread, skip the
            // dispatcher and directly invoke the Action.
            if (_instance.CheckAccess() || _designer == true)
            {
                a();
            }
            else
            {
                _instance.BeginInvoke(a);
            }
        }
    }
}
于 2010-04-06T06:36:20.933 回答
6

如果您使用MVVM 灯光工具包,您可以使用 Extras dll 中 Galasoft.MvvmLight.Threading 命名空间中的 DispatcherHelper 类。它检查访问并为调度程序使用静态属性,类似于 SmartDispatcher。

在您的 App.xaml.cs 启动事件调用中:

DispatcherHelper.Initialize();

然后在任何需要使用调度程序的地方使用:

   DispatcherHelper.CheckBeginInvokeOnUI(() => // do stuff; );
于 2010-12-20T19:46:08.313 回答