【问题标题】:Convert IAsyncOperation to Task [duplicate]将 IAsyncOperation 转换为任务 [重复]
【发布时间】: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


【解决方案1】:

解决方案是引用System.Runtime.WindowsRuntime,有一个同名的扩展方法(AsTask)做同样的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-06
    • 2013-05-06
    • 1970-01-01
    • 2020-11-01
    • 2015-06-28
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多