我想不斷讀取串行端口,並在我的Windows 10通用應用程序(C#)的文本框中獲得輸出。我發現從MS系列樣品此代碼https://github.com/ms-iot/samples/tree/develop/SerialSample/CS:我怎樣才能不斷讀取在Windows 10通用(C#)的串行端口
private async void Listen()
{
try
{
if (serialPort != null)
{
dataReaderObject = new DataReader(serialPort.InputStream);
while (true)
{
await ReadAsync(ReadCancellationTokenSource.Token);
}
}
}
catch (Exception ex)
{
if (ex.GetType().Name == "TaskCanceledException")
{
CloseDevice();
}
}
finally
{
if (dataReaderObject != null)
{
dataReaderObject.DetachStream();
dataReaderObject = null;
}
}
}
private async Task ReadAsync(CancellationToken cancellationToken)
{
Task<UInt32> loadAsyncTask;
uint ReadBufferLength = 1024;
cancellationToken.ThrowIfCancellationRequested();
dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken);
UInt32 bytesRead = await loadAsyncTask;
if (bytesRead > 0)
{
reciveTextBox.Text = dataReaderObject.ReadString(bytesRead);
}
}
但是當我打電話聽()函數與點擊一個按鈕,有時它有時讀端口沒有。
請給出一個解決方案,它會不斷讀取串行端口並在文本框中輸出結果。
MainPage.xaml.cs中的全部代碼是在這裏:http://pastebin.com/dmsTUBmT
儘管此鏈接可能回答問題,但最好在此處包含答案的基本部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – Marusyk