【发布时间】:2021-09-01 20:38:24
【问题描述】:
我正在尝试将 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());
}
}
【问题讨论】:
-
你能使用 System.Runtime.WindowsRuntime 中的 AsTask 方法吗?
-
@John,是的,谢谢,它工作得很好
标签: c# asynchronous async-await extension-methods iasyncoperation