在循环中向IoTHuB发送消息

时间:2018-04-16 11:09:00

标签: uwp arduino async-await azure-iot-hub windows-iot-core-10

我正在尝试开发一个可在Windows IoT核心上运行的UWP应用程序。这个应用程序将读取来自Arduino的一些传感器数据,然后将其作为消息发送到我的azure iothub。我一直在代码中使用异步方法。

private async Task ReadAsync(CancellationToken cancellationToken)
{
        Task<UInt32> loadAsyncTask;
        uint ReadBufferLength = 1024;
        // If task cancellation was requested, comply
        cancellationToken.ThrowIfCancellationRequested();
        // Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
        dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
        using (var childCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
        {
            // Create a task object to wait for data on the serialPort.InputStream
            loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(childCancellationTokenSource.Token);
            // Launch the task and wait
            UInt32 bytesRead = await loadAsyncTask;
            if (bytesRead > 0)
            {
                var tempData = dataReaderObject.ReadString(bytesRead);
                rcvdText.Text = tempData;
                status.Text = "bytes read successfully!";
                await SendDeviceToCloudMessagesAsync(tempData);
            }
        }
    }

SendDeviceToCloudMessagesAsync的定义:

private async Task SendDeviceToCloudMessagesAsync(string data)
    {
        //do some string manipulations on data and create the telemetry object.

        deviceClient = DeviceClient.CreateFromConnectionString(deviceConnString);

            var messageString = JsonConvert.SerializeObject(telemetry);
            var message = new Message(Encoding.ASCII.GetBytes(messageString));

            await deviceClient.SendEventAsync(message);
            await Task.Delay(1000);
     }

这就是调用方法的方法:

  // keep reading the serial input
  while (true)
  {
       await ReadAsync(ReadCancellationTokenSource.Token);
  }

这里的期望是应用程序应继续读取串行输入,并将其连续循环发送到iothub。但问题是它只执行一次,然后返回到UI。如果我删除行await SendDeviceToCloudMessagesAsync(tempData),那么代码继续监听串行输入。所以我理解它与SendEventAsync方法有关。我能够在.net控制台应用程序中循环使用此方法,但我不知道如何在UWP中修复它。

以下是SendEventAsync方法的签名(来自元数据):

public Task SendEventAsync(Message message);

我对异步编程很新。如果我需要在问题中提供额外的输入,请发表评论。

1 个答案:

答案 0 :(得分:0)

你有线程问题。 尝试使用ThreadPool.QueueUserWorkItem来生成一个发送消息的进程。

相关问题