中止/取消ReadValueAsync的安全方法(BluetoothCacheMode.Uncached)

时间:2015-11-06 12:24:57

标签: c# windows-8.1 bluetooth-lowenergy winrt-async

如果没有可用的BLE设备(具有所请求的特定特性),则ReadValueAsync(BluetoothCacheMode.Uncached)会在返回结果之前尝试读取7-8秒。在这种情况下,是否有任何安全的方法来取消/中止任务而不必等待整整7秒?

这是我目前的实施(基于Asynchronously wait for Task<T> to complete with timeout):

int timeout = 1000;
var task = BleCommon.Instance.readCharacteristic(devName, serviceUuid, characteristicUuid, isEncryptionRequired);
if (await Task.WhenAny(task, Task.Delay(timeout)) == task)
{
    // task completed within timeout
    var result = await task;
    // do something with result
}
else
{ 
    // timeout occured
    // do nothing
}

public async Task<List<byte>> readCharacteristic(string deviceName, Guid serviceUuid, Guid characteristicUuid, bool isEncryptionRequired)

是否有人发现此实施存在任何潜在问题?

请注意,readCharacteristic()函数基本上只是ReadValueAsync(BluetoothCacheMode.Uncached)(https://msdn.microsoft.com/en-us/library/windows/apps/dn263758.aspx)的包装函数。我主要担心的是,我不完全确定在上次调用它之前调用ReadValueAsync(BluetoothCacheMode.Uncached)时会发生什么。

0 个答案:

没有答案