只要设备在运行,我就需要一个保持生命的功能。该方法在一个模块中。我感觉它在3-10小时后就停止运行了。
// Async method to send keepalive signals
private static async void SendKeepaliveToCloudMessagesAsync()
{
int keep_alive_counter = 0;
while (true)
{
try
{
String timestamp = DateTimeOffset.UtcNow.ToString("u");
String activity_type = "Device-Keepalive";
// Create JSON message
var telemetryDataPoint = new
{
timestamp,
activity_type,
device_id,
keep_alive_counter
};
var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
var message = new Message(Encoding.ASCII.GetBytes(messageString));
keep_alive_counter++;
// Add a custom application property to the message.
// An IoT hub can filter on these properties without access to the message body.
message.Properties.Add("keepaliveAlert", (keep_alive_counter < 30) ? "true" : "false");
// Send the telemetry message
await s_deviceClient.SendEventAsync(message);
Console.WriteLine("[{0}] > Sending Keepalive message: {1}", DateTimeOffset.UtcNow.ToString("u"), messageString);
await Task.Delay(s_keepaliveInterval * 1000);
}
catch (Exception ex)
{
Console.Error.WriteLine("Send keepalive Failed! {0}", ex);
}
}
}上面的代码可以工作3到10个小时,但是突然停止了,我在IoTHub上没有收到保持活动的消息。
我设法从日志中得到以下消息:
Send keepalive Failed! System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IoT Client'.
at Microsoft.Azure.Devices.Client.Transport.DefaultDelegatingHandler.ThrowIfDisposed()
at Microsoft.Azure.Devices.Client.Transport.DefaultDelegatingHandler.OpenAsync(CancellationToken cancellationToken)
at Microsoft.Azure.Devices.Client.Transport.RetryDelegatingHandler.<>c__DisplayClass32_0.<<OpenAsyncInternal>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Azure.Devices.Client.Transport.RetryDelegatingHandler.EnsureOpenedAsync(CancellationToken cancellationToken)
at Microsoft.Azure.Devices.Client.Transport.RetryDelegatingHandler.<>c__DisplayClass14_0.<<SendEventAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Azure.Devices.Client.Transport.RetryDelegatingHandler.SendEventAsync(Message message, CancellationToken cancellationToken)
at Microsoft.Azure.Devices.Client.InternalClient.SendEventAsync(Message message)
at MotionDetection.Program.SendKeepaliveToCloudMessagesAsync() in /app/Program.cs:line 439发布于 2019-07-28 19:05:36
虽然您看到的错误不应该发生,但我仍然可以回答实际问题:
构建模块以不受限制地发送消息的方式看起来很好,而且一般都能工作。实际上,IoT边缘团队的一个示例与您的版本非常相似,参见这里 ( SendUnlimitedMessages()是true时的情况)。
也许只需遵循他们的例子,并为一个干净的退出策略实现一个关闭处理程序。
https://stackoverflow.com/questions/57233072
复制相似问题