I have a UWP application, I want to use the method in MainPage.xaml.cs
in App.xaml.cs
, for some reason, the method in MainPage.xaml.cs
can't be declared to be static, so I instantiate the MainPage class in App.xaml.cs
, but throw the following exception:
The application invokes an interface that has been organized for another thread。(Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
This is the code in 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();
This is the code in MainPage.xaml.cs:
public async Task<string> myFunction()
{
string back = "this is my code";
return back;
}
How to solve this problem, Thanks
App
code is running in anMTA
(Multi-Thread Apartment) and yourMainPage
needs to run in anASTA
(Application Single-Thread Apartment). But you probably don't want / need to learn about those things (see MSDN if you're curious - note that article is 20 years old!). Why can't you make the function static? There is presumably other code that you're not showing? – Peter Torr - MSFT