问题
I'm getting InvalidOperationException
. This code is running in a thread. I've delegate it to the UI thread to handle the UI. Is the problem occuring because of my resources?
BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri("pack://application:,,,/LiarDice;component/" + imagePath);
logo.EndInit();
currentGuessDice.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(delegate()
{
currentGuessDice.Source = logo;
}));
I changed my code slightly a little and now the error changes to:
Part URI cannot end with a forward slash.
New Code:
currentGuessDice.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(delegate()
{
BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri("pack://application:,,,/LiarDice;component/" + imagePath);
logo.EndInit();
currentGuessDice.Source = logo;
}));
回答1:
Besides that your imagePath
variable my be null
, the problem in your original code is that you create a BitmapImage in a thread other than the UI thread, and then use it in the UI thread.
In order to make this working, you'll have to freeze the BitmapImage:
var logo = new BitmapImage(
new Uri("pack://application:,,,/LiarDice;component/" + imagePath));
logo.Freeze(); // here
currentGuessDice.Dispatcher.Invoke(new Action(() => currentGuessDice.Source = logo));
来源:https://stackoverflow.com/questions/31769728/invalidoperationexception-delegation-ui-thread-c-sharp