我有以下代码从树莓派上的传感器读取温度。
代码是异步的,如果我只删除代码的最后一行,即发送消息的代码,我永远不会得到异常。我的意思是这一行:
await deviceClient.SendEventAsync(message);
private async void InitializeSensors()
{
string calibrationData;
//_periodicTimer.Dispose();
// Inicializar el sensor bmp180
try
{
_bmp180 = new Bmp180Sensor();
await _bmp180.InitializeAsync();
calibrationData = _bmp180.CalibrationData.ToString(); //Retorna una cadena que representa al objeto actual.
if (_periodicTimer == null)
{
_periodicTimer = new Timer(this.TimerCallback, null, 0, readingInterval);
}
}
catch (Exception ex)
{
calibrationData = "Error de dispositivo! " + ex.Message;
}
var task = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
//calibrationDataTextBlock.Text = "";
});
}
public async void TimerCallback(object state)
{
string temperatureText;
// Leer datos del sensor
try
{
var sensorData = await _bmp180.GetSensorDataAsync(Bmp180AccuracyMode.UltraHighResolution);
temperatureText = sensorData.Temperature.ToString("");
//pressureText = sensorData.Pressure.ToString("F2");
temperatureText += "°C";
//pressureText += "hPa - " + BitConverter.ToString(sensorData.UncompestatedPressure);
var temperatureDataPoint = new
{
deviceKey = deviceKey,
deviceName = deviceName,
temperatura = sensorData.Temperature,
fecha = DateTime.Now
};
var messageString = JsonConvert.SerializeObject(temperatureDataPoint);
var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString));
message.Properties["Ambiente"] = ambiente;
////temperatura.Text = temperatureText;
await deviceClient.SendEventAsync(message);
}
catch (Exception ex)
{
temperatureText = "Sensor Error: " + ex.Message;
//pressureText = "Sensor Error: " + ex.Message;
}
//// actualizaciones de la interfaz de usuario... deben ser invocados en el subproceso de interfaz de usuario
var task = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
temperatura.Text = temperatureText;
});
}
如果我删除这些线,我可以看到传感器正在工作,因为文本框已更新为真实温度。
只有当我取消注释 sendmessage 行时,我才会收到异常
我怎样才能解决这个问题?