InvalidOperationException delegation UI Thread C#

梦想与她 提交于 2020-02-06 03:31:15

问题


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

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