首页 > 解决方案 > 类中的 Dispatcher.invoke 问题:C#

问题描述

这是我的代码的一部分:

public void refreshShowCase()
{

    for (int i = 0; i < 12; ++i)
    {
        bitmapImage[i] = new BitmapImage(new Uri(posterURLCollection[i]));
        image[i] = new Image { Source = bitmapImage[i] }; //Error occurs here****
    }
}

当我运行它时,我得到这个错误:调用线程必须是 STA,因为许多 UI 组件都需要这个。

所以我在里面添加我的代码Disapther.Invoke

this.Dispatcher.Invoke((Action)delegate
{
   BitmapImage[] bitmapImage = new BitmapImage[14];
   Image[] image = new Image[14];

   //Do a loop for defining Bitmaps sources
   for (int i = 0; i < 12; ++i)
   {
         bitmapImage[i] = new BitmapImage(new Uri(posterURLCollection[i]));
         image[i] = new Image { Source = bitmapImage[i] };
   }
}

现在我有这个错误:'Dispatcher' 在当前上下文中不存在!

我应该如何解决这个问题?请帮忙。

Update1:​​提到的代码在我创建的类的内部无效!

标签: c#.netwindowsvisual-studio

解决方案


在您的问题中,您在this.Dispatcher.Invoke((Action)delegate自定义类中使用。this指的是该类内部的函数。您的自定义类没有Dispatcher.

而是使用:App.Current.Dispatcher.Invoke((Action)delegate并确保包含此代码的自定义类位于您的App命名空间下。


推荐阅读