【问题标题】:c# async methods with BLEc# BLE异步方法
【发布时间】:2017-10-11 15:50:59
【问题描述】:

我在执行此蓝牙代码时遇到问题。我正在使用这个库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);
    };
});

【问题讨论】:

    标签: c# ios bluetooth async-await


    【解决方案1】:

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

    解决办法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多