【发布时间】: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 年历史了!)。为什么不能将函数设为静态?您可能没有显示其他代码? -
谢谢,目前看来只能用静态方法了