wpf InvalidOperationException:调度程序处理在 ImageOffsetProperty 上暂停

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19589400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:57:05  来源:igfitidea点击:

InvalidOperationException: dispatcher processing is suspended on ImageOffsetProperty

c#wpfdispatcherinvalidoperationexception

提问by jera

I am using C# and WPF and am trying to slide an image strip along the screen. I am being honest, I got the code from some code sample on the Internet and took the parts I needed from it.

我正在使用 C# 和 WPF,并试图沿屏幕滑动图像条。老实说,我从 Internet 上的一些代码示例中获取了代码,并从中取出了我需要的部分。

public double ImageOffset
{
    get
    {
        try
        {
            return (double)this.Dispatcher.Invoke(
               System.Windows.Threading.DispatcherPriority.Background,
               (DispatcherOperationCallback)delegate 
               { return GetValue(ImageOffsetProperty); }, ImageOffsetProperty);
        }
        catch
        {
            return (double)this.GetValue(ImageOffsetProperty);
        }
    }

    set
    {
        this.Dispatcher.BeginInvoke(DispatcherPriority.Background,
            (SendOrPostCallback)delegate 
            { SetValue(ImageOffsetProperty, (object)value); },
            (object)value);
    }
}

Sometimes when the program tries to get the ImageOffsetProperty an InvalidOperationException: Cannot perform this operation while dispatcher processing is suspendedhappens and I have no idea how to fix it.

有时当程序试图获取 ImageOffsetPropertyInvalidOperationException: Cannot perform this operation while dispatcher processing is suspended时,我不知道如何修复它。

I also tried Dispatcher.BeginInvoke, safe the ImageOffsetProperty in a Double and then return it, but it always returned 0.

我也试过Dispatcher.BeginInvoke,将 ImageOffsetProperty 放在 Double 中,然后返回它,但它总是返回 0。

What is causing the InvalidOperationException?

是什么导致的InvalidOperationException

采纳答案by Clemens

How about dropping all the Backgroundstuff and just write a standard dependency property wrapper like this:

如何删除所有的Background东西,只编写一个标准的依赖属性包装器,如下所示:

public double ImageOffset
{
    get { return (double)GetValue(ImageOffsetProperty); }
    set { SetValue(ImageOffsetProperty, value); }
}

When the property is set from a background thread, put the assignment in a Dispatcher.Invokeor Dispatcher.BeginInvokecall.

从后台线程设置属性时,将赋值放入Dispatcher.InvokeorDispatcher.BeginInvoke调用中。

Replace

代替

obj.ImageOffset = someOffset;

by

经过

Dispatcher.Invoke(() => obj.ImageOffset = someOffset);

or

或者

Application.Current.Dispatcher.Invoke(() => obj.ImageOffset = someOffset);

if you don't have direct access to the Dispatcherproperty of some UI element.

如果您无法直接访问Dispatcher某些 UI 元素的属性。