我是C#的新手,並將一些Swift Bluetooth LE代碼轉換爲C#UWP。我是否可以使用await轉換我的代碼而不是使用回調代碼
我有使用異步/等待的代碼工作。但爲了使它與我在Swift中的內容相似,我想我最好是在異步API完成時獲得回調。
例如,SWIFT代碼:
private func connect_to(per : CBPeripheral) {
centralManager?.connect(per, options: nil)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices([transferServiceUUID])
}
第二func被回叫。目前在C#我有這樣的事情:
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.
}
只見引用在C#中使用委託,但它不是我清楚如何使用API調用做到這一點。
給異步等待一個機會,它確實使代碼更具可讀性,並從一個什麼它的視角與代碼的回調版本類似。 –
這個問題還不清楚。您可以創建自定義委託定義,使用Action/Functions或創建回調接口並繼承一個類。但異步方式更具可讀性。 –
我的問題是,我無法弄清楚如何做一個自定義的委託定義。但是,在這一點上,我認爲我確信使它與異步/等待一起工作。 – bobwki