对象引用未设置到对象的实例解决方法

Object reference not set to an instance of an object work around

我正在 Xamain.Forms 中构建一个 BLE 应用程序。我正在使用一个适配器,它根据事件触发许多方法,例如 adapter.DeviceDiscovered 等。过程是:

  1. 扫描设备
  2. 连接到所选设备
  3. 扫描设备上存在的Services
  4. Select一个Service
  5. 在设备上扫描 Characteristics

我现在正在处理第 5 步并且有以下代码:

ChosenService.CharacteristicsDiscovered += (object sender, EventArgs e) => {
    Debug.WriteLine("service.CharacteristicsDiscovered");
    if (characteristics.Count == 0)
        Device.BeginInvokeOnMainThread(() => {
            foreach (var characteristic in ChosenService.Characteristics) {
                characteristics.Add(characteristic);
            }
        });
};

但是,由于在第 4 步完成之前 ChosenService 为 null,因此在打开应用程序时,此方法会抛出 Object reference not set to an instance of an object 异常。我该如何解决这个问题?理想情况下,我想我设置ChosenService后需要读取方法,我应该怎么做?

检查 Activity Lifecycle 看看是否有一个状态可以满足您的要求
如果没有,请考虑使用任务和设置程序 运行 完成任务后

LoadData().ContinueWith(task => {
     BeginInvokeOnMainThread(() => {
         _myData = task.Result;
         // Do Some UI stuff or something else
     });
}

查看更多关于 Tasks.ContinueWith here