【问题标题】:Dispatcher.invoke problem in a class : C#类中的 Dispatcher.invoke 问题:C#
【发布时间】:2019-02-19 10:46:33
【问题描述】:

这是我的代码的一部分:

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:​​提到的代码在我创建的类的内部!

【问题讨论】:

  • System.Windows.Application.Current.Dispatcher.Invoke 工作吗?
  • @Adam:当我使用它时,我得到这个:“应用程序”类型中不存在“当前”
  • 您收到编译时错误或运行时错误?
  • @SoumenMukherjee:当我不使用 Dispatcher 时,我会收到我提到的运行时错误:调用线程必须是 STA,因为许多 UI 组件都需要这个。但是,当我使用 Dispatcher 时,This.Dispatcher 下方会出现一条红线,上面写着:“Dispatcher”在当前上下文中不存在!
  • 我的水晶球说你写了一个 UWP 应用,而不是 WPF 应用。 stackoverflow.com/questions/16477190/…

标签: c# .net windows visual-studio


【解决方案1】:

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

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

【讨论】:

  • 我应该如何确保该类属于 App 命名空间?能具体说明一下吗?
  • 当我使用这个App.Current.Dispatcher.Invoke((Action)delegate 时,Current 下会出现一行,并说应用上下文中不存在“当前”!我该如何解决这个问题?
  • 如果这个类在 .cs 文件中,只要确保它在 namespace myAppname 的花括号内就可以了。
  • 什么 .net 版本,您使用的是控制台应用程序还是 Windows 应用程序?这是 WPF 还是 UWP 应用?
  • 它是 WPF 应用程序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-03
  • 2011-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多