【问题标题】:How to solve "The application invokes an interface that has been organized for another thread"如何解决“应用程序调用已为另一个线程组织的接口”
【发布时间】:2018-06-13 19:11:35
【问题描述】:

我有一个UWP应用程序,我想在App.xaml.cs中使用MainPage.xaml.cs中的方法,由于某种原因,MainPage.xaml.cs中的方法不能声明为静态,所以我实例化MainPage类在App.xaml.cs,但抛出以下异常:

应用程序调用一个已组织好的接口 对于另一个线程。(来自 HRESULT 的异常:0x8001010E (RPC_E_WRONG_THREAD))

这是App.xaml.cs中的代码:

//"MainPage MP = new MainPage()"Error:The application invokes an interface that has been organized for another thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
MainPage MP = new MainPage();
string mess = await MP.myFunction();

这是 MainPage.xaml.cs 中的代码:

public async Task<string> myFunction()
{
   string back = "this is my code";
   return back;
}

如何解决这个问题,谢谢

【问题讨论】:

  • 也许您应该使用 ViewModelClass。你可以绑定到 MainPage 并在需要的地方使用它...
  • 基本问题是您的App 代码在MTA(多线程单元)中运行,而您的MainPage 需要在ASTA(应用程序单线程单元)中运行)。但是您可能不希望/不需要了解这些内容(see MSDN if you're curious - 请注意该文章已有 20 年历史了!)。为什么不能将函数设为静态?您可能没有显示其他代码?
  • 谢谢,目前看来只能用静态方法了

标签: c# uwp


【解决方案1】:

您绝对应该将您需要使用的方法从MainPage 移出,以防它包含共享的业务逻辑,在理想情况下实际上不属于MainPage,代码隐藏文件应该在没有代码的情况下清晰,除非有一些仅 UI 代码,用于操作实际的页面控件。

通常业务逻辑位于服务中,然后从绑定到 UI 的视图模型类中调用这些服务。这是关注点的最佳分离。当您有一个方法,即在一个页面上并且您需要从不同的页面使用它时,它显然是一个业务逻辑方法,它应该在一个服务类中,可以从两个地方调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    相关资源
    最近更新 更多