我正在尝试将 IAsyncOperation 转换为 Task,我首先想到的是创建一个扩展方法,它简单地包装 GetResults 方法并返回 Task.FromResult 但我不知道我是否做得正确或不。
关于如何正确编写 AsTask 的任何建议?
public static async Task<string> PairDeviceAsync(ulong Address)
{
var device = await BluetoothLEDevice.FromBluetoothAddressAsync(Address).AsTask();
if (device != null)
{
device.DeviceInformation.Pairing.Custom.PairingRequested += (DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args) => args.Accept();
var result = await device.DeviceInformation.Pairing.Custom.PairAsync(DevicePairingKinds.ConfirmOnly).AsTask();
return result.Status.ToString();
}
else
{
return string.Format("Device address:{0} not found", Address);
}
}
public static class Helpers
{
public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source)
{
return Task.FromResult(source.GetResults());
}
}