Reputation: 151
I am having below lines of code:
private static IReadOnlyList<GattDeviceService> GetGattServicesAsync(BluetoothLEDevice device, bool useUnCachedServices)
{
GattDeviceServicesResult services = useUnCachedServices ? device.GetGattServicesAsync(BluetoothCacheMode.Uncached).GetResults() : device.GetGattServicesAsync().GetResults();
Global.Log.TraceOut();
// Return list anyway
return services.Services;
}
This is called from below line:
var services = ApiInformation.IsMethodPresent("Windows.Devices.Bluetooth.BluetoothLEDevice", "GetGattServicesAsync", 1) ?
GetGattServicesAsync(device, useUnCachedServices) :
device.GattServices;
I am using GetGattServicesAsync() call used to retrieve services from mobile device.In one of scenario,I was unable to gets services from Mobile device and UI stuck there.I want to suspend this call if the response won't come in 10 seconds. I thought to achieve this using Task and cancellation token.But found that this call is working only when task is run as synchronously and thus i was not able to cancel the task using cancellation token.Please help to achieve this,May be in simplest way:
Referred links: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time
How to cancel a task that is waiting with a timeout without exceptions being thrown
Upvotes: 1
Views: 385
Reputation: 260
I hope this code helps you.
you can use Task
private static IReadOnlyList<GattDeviceService>GetGattServicesAsync(BluetoothLEDevice device, bool useUnCachedServices)
{
var CancellationTokenSource = new CancellationTokenSource();
var CancellationToken = new CancellationTokenSource.Token;
var GetResults = task.Run(async ()=> awite useUnCachedServices ? device.GetGattServicesAsync(BluetoothCacheMode.Uncached).GetResults() : device.GetGattServicesAsync().GetResults(),_cancellationToken);
WaitHandle.WaitAny(new[] { cancellationTokenSource.Token.WaitHandle }, TimeSpan.Fromseconds(10));
Global.Log.TraceOut();
// Return list anyway
return services.Services;
}
With work As soon as _cancellationToken = true Tack No longer continues.
Upvotes: 1