简体   繁体   中英

Call non static method from different non static class

I have Mainpage.cs where I have method public void websocketRequestGetListOfUni() and then I have this class

public class RegisterResponseReceiverRegisterDevice : ResponseReceiver
    {
        public override void onResponseReceived(byte[] header, byte[] response)
        {
            RegisterResponse rr = RegisterResponse.ParseFrom(response);

            var t = new MainPage();
            t.websocketRequestGetListOfUni();
        }
        public override void onError() { }
    }

public void websocketRequestGetListOfUni()
    {
        IntMessage req = IntMessage.CreateBuilder().SetValue(1).Build();
        WebSocketClient.write(3, 7, req, new RegisterResponseReceiverGetListOfUni());
    }

I want call method websocketRequestGetListOfUni() in class RegisterResponseReceiverRegisterDevice but when I call it I get at var t = new MainPage();

error

The application called an interface that was assigned to a different thread.

I also try use

this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => mymethoc);

but Dispather is not recognized. Any idea how call my method?

here is Mainpage for better understanding: https://www.dropbox.com/s/oz6qb0naa0u0for/Mainpage.cs.txt

var t = new MainPage(); is going to instanciate the page (including the UI part (which is instanciated by the Initialise call in MainPage constructor)) so it's a very bad idea to instanciate it just to get access to a method. I strongly sugest that you to reachitecture your code so that you don't need to do that. Particularly you should look at the MVVM patern.

If you still want to do that, you can use the following code to dispatch your method on the UI thread:

await CoreApplication.MainView.CoreWindow.RunAsync(CoreDispatcherPriority.Normal, () => mymethoc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM