InvalidOperationException: dispatcher processing is suspended on ImageOffsetProperty

空扰寡人 提交于 2019-12-11 12:53:56

问题


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.

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 suspended happens and I have no idea how to fix it.

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

What is causing the InvalidOperationException?


回答1:


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

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.Invoke or Dispatcher.BeginInvoke call.

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 Dispatcher property of some UI element.



来源:https://stackoverflow.com/questions/19589400/invalidoperationexception-dispatcher-processing-is-suspended-on-imageoffsetprop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!