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. 安全更新UItextBoxOutput2.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);elseupdateAction();
}// 使用
SafeUpdate(textBox1, () =>
{textBox1.Text = "Updated safely";textBox1.BackColor = Color.Green;
});
3. 什么情况下使用委托