【发布时间】:2018-06-22 02:06:10
【问题描述】:
如何让我的代码更精简,只用一个 Invoke 方法?
private void DecodeTHR(byte[] serialInput)
{
startVoltage.Invoke((MethodInvoker)(() => startVoltage.Value = serialInput[2]));
endVoltage.Invoke((MethodInvoker)(() => endVoltage.Value = serialInput[3]));
mode.Invoke((MethodInvoker)(() => mode.SelectedIndex = serialInput[4]));
if (serialInput[5] == 255)
assistLevelTH.Invoke((MethodInvoker)(() => assistLevelTH.SelectedIndex = 0));
else
assistLevelTH.Invoke((MethodInvoker)(() => assistLevelTH.SelectedIndex = serialInput[5] + 1));
if (serialInput[6] == 255)
speedLimitTH.Invoke((MethodInvoker)(() => speedLimitTH.SelectedIndex = 0));
else
speedLimitTH.Invoke((MethodInvoker)(() => speedLimitTH.SelectedIndex = serialInput[6] - 14));
startCurrentTH.Invoke((MethodInvoker)(() => startCurrentTH.Value = serialInput[7]));
// RestartPort();
if (next_op == rdSingle)
MessageBox.Show("Throttle Handle flash read successful", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
{
MessageBox.Show("Flash read successful", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
next_op = rdIgnore;
}
}
到目前为止,我找不到任何其他方法,但我确信有一种方法可以在方法内部进行一次调用,然后可以从主 Form 类更新任意数量的 GUI 组件.
由于我有很多这些功能,有人可以提供一个使用我的代码的示例吗?
【问题讨论】:
-
不要调用。将值写入一些共享变量。让 GUI 通过计时器轮询 Udpates 的这些变量。对这些变量的所有调用应用一些锁定,当然 (docs.microsoft.com/en-us/dotnet/csharp/language-reference/…)
-
你为什么还要在后台线程中运行它呢?据我所知,您没有执行任何繁重的计算/阻塞任务。
-
@VisualVincent 该函数在 SerialPort.DataReceived 事件处理程序中运行。
-
请参阅下面的答案以获取更简单的调用方式。
标签: c# multithreading user-interface