Convert IAsyncOperation to Task

357 Views Asked by At

I'm trying to convert an IAsyncOperation to Task, the first thing that I had in mind is to create an extension method that simply wrap the GetResults method and return the Task.FromResult but I don't know if I'm doing things properly or not.

Any suggestions of how can I write the AsTask properly ?

    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());
        }
    }
1

There are 1 best solutions below

0
On

The solution was to reference the System.Runtime.WindowsRuntime, there is an extension method with the same name (AsTask) that does the same thing.