这算是第一个写的c#项目 写的很乱毫无章法 如果有大神刷到希望指点一二
我的ui线程用来一直跑组态图 所以我每个操作都是重新搞个线程然后释放 因为我是和设备打交道的所有我没有考虑资源利用什么的;
1、声明一个委托
public delegate Dictionary<string, string> Cal(SerialPort serialPort, string s, string changjia);
2、写订阅委托的方法
public Dictionary<string, string> TriggerDelegateT(string s, string changjia)
{
//初始化订阅的返回值
Dictionary<string, string> d = new Dictionary<string, string>();
if (!this.serialPort1.IsOpen)
{
MessageBox.Show("请打开串口");
return d;
}
if (cal != null)//如果委托不为空
{
//委托当前表号对应的textBox
TextBox textBox = indexAndDeviceMap[s];
//对应的颜色块
Button button = allIndexDevicoMap[textBox.TabIndex];
changeColor(button, Color.Yellow);
int a = 3;//每个命令发三次
while (a > 0)//定义三次
{
try
{
//执行委托
d = cal.Invoke(this.serialPort1, s, changjia);
//委托执行成功颜色变绿
changeColor(button, Color.Green);
//logTextBox2.AppendText(",操作成功" + Environment.NewLine);
return d;
}
catch
{
//委托执行失败判断是否是最后执行
if (a == 1)
{//是最后一次执行颜色变成红色
changeColor(button, Color.Red);
logger.WriteLog("表号" + s + "三次操作失败", LogUtil.LogLevel.Info);
// logTextBox3.AppendText(",操作失败" + Environment.NewLine);
}
else
{//在执行过程中颜色是黄色
changeColor(button, Color.Yellow);
}
}
a--;
}
}
return d;
}
3、使用委托
public void button16_Click(object sender, EventArgs e)
{
Task.Run(() => {
addDevico(sender, e);
string changjia = this.textBox1.Text;
cal = new Cal(DeliveryFunctionUtil.entryCali);
for (int i = 0; i < getCheckDevicoList.Count; i++)
{
this.Invoke(new MethodInvoker(delegate
{
logTextBox3.AppendText(DateTime.Now + " " + "表号:" + getCheckDevicoList[i] + "进入检定操作");
}));
TriggerDelegateT(getCheckDevicoList[i], changjia);
}
});
}
5、委托的函数
最后我真的觉得c#的委托和我们java的代理好像呀,至少我看来很像哈哈哈哈哈哈哈,下面是文言一心的回答,如果大佬有不同的见解 欢迎指点我这个菜狗