c# - Call async method with callback from sync UI thread -
this question has answer here:
im stuck here... have xaml page ui , want call async function everytime user interacts ui.
use signalr networking:
public static class protocolclient { private static hubconnection hubconnection; private static ihubproxy protocolhubproxy; public static async void connect(string server) { hubconnection = new hubconnection(server); protocolhubproxy = hubconnection.createhubproxy("protocolhub"); protocolhubproxy.on<body>("bodieschanged", body => //call callback return body ); await hubconnection.start(); //wait connection } public static async void sendtouch(touch touch) { body body = await protocolhubproxy.invoke<body>("getbodyfortouch", touch); //call callback return body } }
ui:
public sealed partial class mainpage : page { [...] private void canvas_pointerpressed(object sender, pointerroutedeventargs e) { [...] switch (ptrpt.pointerdevice.pointerdevicetype) { case windows.devices.input.pointerdevicetype.mouse: if (ptrpt.properties.isleftbuttonpressed) { //call sendtouch } break; default: break; } [...] } }
i need callback can modify ui. how can call connect , sendtouch out of ui , pass them callback?
you don't need callback. add code after await hubconnection.start();
statement. method 'cut in multiple methods' , 'continue' after await comes back. await
works blocking statement, not freeze gui.
public static async void connect(string server) { hubconnection = new hubconnection(server); protocolhubproxy = hubconnection.createhubproxy("protocolhub"); protocolhubproxy.on<body>("bodieschanged", body => //call callback return body ); await hubconnection.start(); //wait connection // add code here. }
when handling commands async (from gui events), don't forget disable controls prevent executing command more ones.
Comments
Post a Comment