问题
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