我的C#mainwindow在单击按钮时启动taskfactory任务。 该任务应该从串行设备收集数据,但不仅仅是一次。 它应该在"实时"中收集数据。 串行模块向该串行设备发送请求。当设备回答时,它应该将数据返回主窗口(我用事件尝试了它)并再次开始收集数据: 开始任务:
private void menuStartLog_Click(object sender, RoutedEventArgs e)
{
Librarys.SerialCom Comport = new Librarys.SerialCom();
Task<string> serialThread = Task<string>.Factory.StartNew(() => Comport.ADVInfo(), TaskCreationOptions.LongRunning);
textBoxMain.Text = serialThread.Result;
}
此方法称为:
public string ADVInfo()
{
openConnection();
if (Comport.IsOpen)
{
Comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
while (true)
{
Console.WriteLine("Serial Task started.");
byte[] SerialRequest = new byte[3] { 0xF0, 0x02, 0x0D };
Comport.Write(SerialRequest.ToString());
Console.WriteLine("Serial Thread completed.");
//Here the task should return data to the mainwindow and request new data
}
}
return ("No open Comport!!!");
}
private static void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
}
但串口通信的线程阻塞了主线程。 我可以在主线程中没有等待的情况下返回数据,例如举办活动?
答案 0 :(得分:1)
Instead of blocking with .Result
, you should await
the Task
created by StartNew
. That way, control is yielded back to the message loop while the operation executes:
private async void menuStartLog_Click(object sender, RoutedEventArgs e)
{
Librarys.SerialCom Comport = new Librarys.SerialCom();
Task<string> serialThread = Task<string>.Factory.StartNew(() => Comport.ADVInfo(), TaskCreationOptions.LongRunning);
textBoxMain.Text = await serialThread;
}
If you want to generate multiple strings from the ComPort
, you can return an IEnumerable<string>
using yield return
.