1. 例子1
private void UdpRxCallBackFunc(UdpDataStruct info)
{
// 1. 前置检查防止无效调用
if (textBoxOutput2.IsDisposed || !textBoxOutput2.IsHandleCreated)
return;
// 2. 使用正确的委托类型
Invoke(new Action(() =>
{
// 3. 双重检查确保安全
if (textBoxOutput2.IsDisposed) return;
try
{
// 4. 安全更新UI
textBoxOutput2.Text = csdataUtil.ByteArrayToHexStr(info.buf, 0, info.length);
}
catch (Exception ex)
{
// 5. 异常处理(可替换为日志记录)
Console.WriteLine($"UDP更新失败: {ex.Message}");
}
}));
}
2. 例子2,安全更新封装方法
public static void SafeUpdate(Control control, Action updateAction)
{
if (control.InvokeRequired)
control.Invoke(updateAction);
else
updateAction();
}
// 使用
SafeUpdate(textBox1, () =>
{
textBox1.Text = "Updated safely";
textBox1.BackColor = Color.Green;
});
3. 什么情况下使用委托