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
You should definitely move the method you need to use from MainPage
in case it contains a shared business logic which actually not part of MainPage
in the ideal world, code-behind files should be clear without code, barring some UI-only code, which manipulates the actual page controls.
Usually business logic is in services which are then called from view models classes that are bound to the UI. This is optimal separation of concerns. When you have a method, that is on a page and you need to use it from a different page, it is clearly a business logic method, that should rather be in a service class, that can be called from both places.
User contributions licensed under CC BY-SA 3.0