c# - Can I convert my code using await to use call-backs instead -


i new @ c#, , converting swift bluetooth le code c# uwp.

i have code working uses async/await. make similar have in swift, think i'd ideally callback when apis async complete.

for example, swift code:

private func connect_to( per : cbperipheral) {     centralmanager?.connect( per, options: nil) }  func centralmanager(_ central: cbcentralmanager, didconnect peripheral: cbperipheral) {     peripheral.delegate = self     peripheral.discoverservices([transferserviceuuid]) } 

the second func call-back. in c# have things this:

private async void connectbyid_oraddr( uint64 btaddr) {   btledev = await bluetoothledevice.frombluetoothaddressasync(btaddr);   if (btledev == null) {      // todo: failure notifications...      return;   }    gattdeviceservicesresult result =        await btledev.getgattservicesasync(bluetoothcachemode.uncached);   // etc. } 

i saw references using delegates in c#, wasn't clear me how api calls.

you can use continuewith chain tasks in c# same way promisses chained then in javascript.

private static void connectbyid_oraddr2(uint64 btaddr) {     bluetoothledevice.frombluetoothaddressasync(btaddr)         .continuewith(btledevtask => // callback when first task completes         {             var btledev = btledevtask.result;             if (btledev == null)             {                 // todo: failure notifications...                 return task.fromresult<gattdeviceservicesresult>(null);             }             return btledev.getgattservicesasync(bluetoothcachemode.uncached);         })         .unwrap()         .continuewith(resulttask =>// callback when second task completes         {             var result = resulttask.result;             console.writeline("result:" + result);         }); } 

oppinion:

please not use continuewith version unless there reason it. find style of code hard follow , prefer async/await version time. should try embrace features of programming language use instead of trying make code language worked in.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -