繁体   English   中英

带有 BLE 的 c# 异步方法

[英]c# async methods with BLE

我在踩这个蓝牙代码时遇到了麻烦。 我正在使用这个库https://github.com/xabre/xamarin-bluetooth-le 它适用于 android (samsung SM G900V Api 23),但是当我在 iOS (iphone 6 10.3) 上运行它时,除非我添加断点,否则永远不会触发更新。 我尝试了几种不同的方法,但我是 C# 和线程的新手。 我究竟做错了什么?

public async void ConnectToDeviceService(IDevice device)
{
    service = await device.GetServiceAsync(Guid.Parse(_UUIDS.SERVICE_UUID));

    infoCharacter = await service.GetCharacteristicAsync(Guid.Parse(_UUIDS.DEVICE_INFO_UUID));
    infoCharacter.ValueUpdated += (o, args) =>
    {
        var bytes = args.Characteristic.Value;
        Console.WriteLine("Characteristic Value: {0}", bytes);
        PrintByteArray(bytes);
    };

    await infoCharacter.StartUpdatesAsync();
}

也试过这个

await infoCharacter.StartUpdatesAsync().ContinueWith(result =>
{
    infoCharacter.ValueUpdated += (o, args) =>
    {
        var bytes = args.Characteristic.Value;
        Console.WriteLine("Characteristic Value: {0}", bytes);
        PrintByteArray(bytes);
    };
});

好的,所以我找到了一个解决方案,但我不完全理解为什么 iOS 上似乎在将事件处理程序添加到变量和更新开始之间存在竞争条件? 我在安卓设备上不会出现这个问题。

解决方案:

public async void ConnectToDeviceService(IDevice device)
{
    service = await device.GetServiceAsync(Guid.Parse(_UUIDS.SERVICE_UUID));

    infoCharacter = await service.GetCharacteristicAsync(Guid.Parse(_UUIDS.DEVICE_INFO_UUID));
    infoCharacter.ValueUpdated += (o, args) =>
    {
        var bytes = args.Characteristic.Value;
        Console.WriteLine("Characteristic Value: {0}", bytes);
        PrintByteArray(bytes);
    };

    await Task.Delay(1000);
    await infoCharacter.StartUpdatesAsync();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM