0
votes

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

1
Maybe you should work with a ViewModelClass. This you could bind to MainPage and use it where you need it...thezapper
The basic problem is that your App code is running in an MTA (Multi-Thread Apartment) and your MainPage needs to run in an ASTA (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
thank you,It seems that the static method can only be used at the momentValues

1 Answers

1
votes

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.