我在C#中有一个表单应用程序,它可以在UI线程上完成所需的操作。它的计算成本不高,但是相当耗时,因为它等待来自其他系统的响应并在此期间锁定UI。
以下是我日常工作的片段。
private void btnRun_Click(object sender, EventArgs e)
{
TextAppend("Checking Laser Marker TCP/IP...");
foreach(string t in Steps)
{
var itm = new ListViewItem(t);
listView1.Items.Add(itm);
}
listView1.Items[0].BackColor = Color.PaleGoldenrod;
progressBar1.Value = 0;
LabelShows(1);
//Check the TCP/IP connection
progressBar1.Value = 21;
bool checkIP = RunModule.CheckConnection("GI SN", IP, port, this);
if (checkIP == false)
{
listView1.Items[0].BackColor = Color.Red;
MessageOK("Failed to connect to the Laser Marker! Please check IP, Port and serial numbers match the Laser marker.", "warn");
LabelShows(0);
return;
}
}
部分:
bool checkIP = RunModule.CheckConnection("GI SN", IP, port, this);
if (checkIP == false)
{
listView1.Items[0].BackColor = Color.Red;
MessageOK("Failed to connect to the Laser Marker! Please check IP, Port and serial numbers match the Laser marker.", "warn");
LabelShows(0);
return;
}
以类似的方式在具有不同功能的例程中进一步发生几次。所有函数都来自不同的类。
我已经考虑过使用backgroundworkers但是这些报告的进度而不是bool。我看过Task.Run()
,但我看不到实现它的方法。任何人都可以就如何更好地构建我的日常工作提供建议吗?
答案 0 :(得分:1)
您可以使用BackgroundWorker实现您的目标
密钥为DoWorkEventArgs
,其属性Result
会传递给RunWorkerCompleted
事件。 (RunWorkerCompleted
事件在UI线程中运行):
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
...
e.Result = RunModule.CheckConnection("GI SN", IP, port, this);
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var checkIP = (bool) e.Result;
if (checkIP == false)
{
listView1.Items[0].BackColor = Color.Red;
MessageOK("Failed to connect to the Laser Marker! Please check IP, Port and serial numbers match the Laser marker.", "warn");
LabelShows(0);
}
}