110,536
社区成员
发帖
与我相关
我的任务
分享
private static DispatcherOperationCallback exitFrameCallback = new DispatcherOperationCallback(ExitFrame);
/// <summary>
/// Processes all UI messages currently in the message queue.
/// </summary>
public static void DoEvents()
{
DispatcherFrame nestedFrame = new DispatcherFrame();
DispatcherOperation exitOperation = Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, exitFrameCallback, nestedFrame);
Dispatcher.PushFrame(nestedFrame);
if (exitOperation.Status != DispatcherOperationStatus.Completed)
{
exitOperation.Abort();
}
}
private static Object ExitFrame(Object state)
{
DispatcherFrame frame = state as DispatcherFrame;
// Exit the nested message loop.
frame.Continue = false;
return null;
}
var data = await ReceiveDatas(.....);
去UI显示(data);
这类省得写 BeginInvoke 的代码也很常见了。这里的关键就在于 await 机制,根本不是阻塞的,而是异步的。这样当异步回调而获得 data 之后,又去主线程进行显示 data 操作了。
关键就在于异步知识。不是死守着同步、阻塞思路去“设计解法”。while (true)
{
while(SerialPort.BytesToRead <XXX)
{
//串口可读取数据不足则等待,等待超时则认为工作流程结束,结束时return
}
DoEvents();
//接收AD,经转换后显示数值并绘制实时曲线
//刷新曲线和数据,每秒三次即可保证连贯性,刷新后须 DoEvents
//……………其它处理…………………………………
}