-
参考:C#子线程中更新ui
-
C#测试
/// <summary>
/// 读(ASYNC),根据输入的变量名,读变量值
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void button1_Click(object sender, EventArgs e)
{
string plcVar = textBox1.Text.Trim();
string VarType = comboBox1.Text;
Debug.WriteLine("读变量(ASYNC)Mian Thread start, 线程ID:{0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
try
{
await TaskAsyncReadAny( plcVar, VarType);
Debug.WriteLine("读变量(ASYNC),Mian Thread end,线程ID:{0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public async Task TaskAsyncReadAny(string plcVar,string VarType)
{
await Task.Run(()=>
{
Debug.WriteLine("TaskAsyncReadAny Thread start, 线程ID:{0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
string result;
switch (VarType)
{
case "BOOL":
TcVar<bool> tcVar1 = new TcVar<bool>(this.tcAdsPlcServer1.tcAdsPlcClient, plcVar);
result = tcVar1.RemoteValue.ToString();
break;
case "INT":
TcVar<short> tcVar2 = new TcVar<short>(this.tcAdsPlcServer1.tcAdsPlcClient, plcVar);
result = tcVar2.RemoteValue.ToString();
break;
case "UIINT":
TcVar<ushort> tcVar3 = new TcVar<ushort>(this.tcAdsPlcServer1.tcAdsPlcClient, plcVar);
result = tcVar3.RemoteValue.ToString();
break;
case "UDINT":
TcVar<uint> tcVar4 = new TcVar<uint>(this.tcAdsPlcServer1.tcAdsPlcClient, plcVar);
result = tcVar4.RemoteValue.ToString();
break;
case "REAL":
TcVar<float> tcVar5 = new TcVar<float>(this.tcAdsPlcServer1.tcAdsPlcClient, plcVar);
result = tcVar5.RemoteValue.ToString();
break;
case "LREAL":
TcVar<double> tcVar6 = new TcVar<double>(this.tcAdsPlcServer1.tcAdsPlcClient, plcVar);
result = tcVar6.RemoteValue.ToString();
break;
default:
throw new Exception("请设置变量类型");
}
//
Action<string> action = new Action<string>((string str) => {textBox2.Text = str;MessageBox.Show(str);});
textBox2.Invoke(action,new object[] { result });
});
Debug.WriteLine("TaskAsyncReadAny Thread end, 线程ID:{0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
}
- 执行结果
读变量(ASYNC)Mian Thread start, 线程ID:1
TaskAsyncReadAny Thread start, 线程ID:9
TaskAsyncReadAny Thread end, 线程ID:1
读变量(ASYNC),Mian Thread end,线程ID:1