新增遙控器訊號序列(多緒排程)
This commit is contained in:
parent
5db51dda99
commit
dd2a0f3d7b
@ -1,5 +1,6 @@
|
||||
using System.IO.Ports;
|
||||
using System.Text;
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace DualScreenDemo
|
||||
{
|
||||
@ -48,6 +49,10 @@ namespace DualScreenDemo
|
||||
|
||||
// 綁定資料接收事件
|
||||
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
|
||||
AppDomain.CurrentDomain.ProcessExit += (s, e) =>
|
||||
{
|
||||
cts.Cancel();
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
@ -61,6 +66,10 @@ namespace DualScreenDemo
|
||||
}
|
||||
|
||||
|
||||
private readonly ConcurrentQueue<string> commandQueue = new();
|
||||
public readonly CancellationTokenSource cts = new();
|
||||
private bool isProcessing = false;
|
||||
|
||||
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
|
||||
{
|
||||
try
|
||||
@ -68,19 +77,14 @@ namespace DualScreenDemo
|
||||
SerialPort sp = (SerialPort)sender;
|
||||
|
||||
if (!sp.IsOpen)
|
||||
{
|
||||
// Console.WriteLine("串列埠未開啟,無法接收資料。");
|
||||
return;
|
||||
}
|
||||
|
||||
int bytesToRead = sp.BytesToRead;
|
||||
if (bytesToRead > 0)
|
||||
{
|
||||
|
||||
byte[] buffer = new byte[bytesToRead];
|
||||
int bytesRead = sp.Read(buffer, 0, bytesToRead);
|
||||
|
||||
|
||||
StringBuilder hexData = new StringBuilder(bytesRead * 2);
|
||||
for (int i = 0; i < bytesRead; i++)
|
||||
{
|
||||
@ -88,24 +92,18 @@ namespace DualScreenDemo
|
||||
}
|
||||
|
||||
string indata = hexData.ToString();
|
||||
// Console.WriteLine($"接收到的資料 (Hex): {indata}");
|
||||
|
||||
Console.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 遙控器: {indata}");
|
||||
|
||||
Task.Run(() =>
|
||||
// 將資料放入佇列
|
||||
commandQueue.Enqueue(indata);
|
||||
|
||||
// 如果尚未啟動處理迴圈,則啟動
|
||||
if (!isProcessing)
|
||||
{
|
||||
try
|
||||
{
|
||||
commandHandler.ProcessData(indata);
|
||||
isProcessing = true;
|
||||
Task.Run(ProcessQueueAsync);
|
||||
}
|
||||
catch (Exception processEx)
|
||||
{
|
||||
Console.WriteLine($"處理資料時發生錯誤: {processEx.Message}");
|
||||
}
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
// Console.WriteLine("未接收到任何資料。");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@ -113,6 +111,27 @@ namespace DualScreenDemo
|
||||
Console.WriteLine($"接收資料時發生錯誤: {ex.Message}");
|
||||
}
|
||||
}
|
||||
private async Task ProcessQueueAsync()
|
||||
{
|
||||
while (!cts.Token.IsCancellationRequested)
|
||||
{
|
||||
while (commandQueue.TryDequeue(out var cmd))
|
||||
{
|
||||
try
|
||||
{
|
||||
commandHandler.ProcessData(cmd);
|
||||
}
|
||||
catch (Exception processEx)
|
||||
{
|
||||
Console.WriteLine($"處理資料時發生錯誤: {processEx.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
await Task.Delay(10); // 避免 CPU 空轉
|
||||
}
|
||||
cts.Cancel();
|
||||
isProcessing = false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user