InvalidOperationException委托UI线程c#

本文关键字:线程 UI 委托 InvalidOperationException | 更新日期: 2023-09-27 18:06:00

我得到了InvalidOperationException。此代码在线程中运行。我把它委托给UI线程来处理UI。问题的发生是因为我的资源吗?

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;
}));

我稍微改变了一下代码,现在错误变成了:

Part URI cannot end with a forward slash.
新代码:

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;
                }));

InvalidOperationException委托UI线程c#

除了你的imagePath变量我的null,在你的原始代码的问题是,你创建一个BitmapImage在一个线程以外的UI线程,然后在UI线程中使用它。

BitmapImage是一个DispatcherObject,这意味着它具有线程亲和性。由于它也是一个Freezable,您可以冻结它,以便使创建它的线程以外的线程可以访问它:

var logo = new BitmapImage(
    new Uri("pack://application:,,,/LiarDice;component/" + imagePath));
logo.Freeze(); // here
currentGuessDice.Dispatcher.Invoke(new Action(() => currentGuessDice.Source = logo));