【发布时间】:2019-04-04 03:22:12
【问题描述】:
我在下面有一个代码循环遍历包含服务器和服务名称的 datagridview 中的每一行,并使用 ServiceController 引用检查每个服务的状态并返回单元格上的值。
For Each dgvrow As DataGridViewRow In DataGridView1.Rows
myController = New ServiceController With {
.MachineName = dgvrow.Cells(0).Value,
.ServiceName = dgvrow.Cells(1).Value
}
dgvrow.Cells(2).Value = myController.Status.ToString
Next
这可行,但它是按顺序运行的,每个线程在进入下一行之前需要时间来完成,所以我想并行运行它。
我在这里搜索并偶然发现了 Parallel.ForEach,但我找不到正确的代码/组合来完成这项工作。
我最初的尝试是
Parallel.ForEach(dgvrow as DataGridViewRow in DatagridView1.Rows
Sub(myServer)
myController = New ServiceController With {
.MachineName = dgvrow.Cells(0).Value,
.ServiceName = dgvrow.Cells(1).Value
}
dgvrow.Cells(2).Value = myController.Status.ToString
End Sub
)
这绝对是错误的,不知道在 ForEach 部分后面放什么
预期结果应如下所示,我希望服务状态列同时填满。
<table border=1>
<tr>
<th>Server Name</th>
<th>Service Name</th>
<th>Service Status</th>
</tr>
<tr>
<th>Server 1</th>
<th>Service 1</th>
<th>Not Running</th>
</tr>
<tr>
<th>Server 2</th>
<th>Service 2</th>
<th>Running</th>
</tr>
<tr>
<th>Server 3</th>
<th>Service 3</th>
<th>Not Running</th>
</tr>
</table>
【问题讨论】:
-
A
DataGridView是一个 UI 元素 - 您不能从 UI 以外的任何线程访问它。你不能在上面使用Parallel.ForEach。你想计算什么让你想要并行计算? -
您是否正在尝试实时更新状态?
-
最终,是的。我正在尝试弄清楚如何并行获取状态,因为这将在 20 多台服务器的列表上运行,并且需要一些时间来检查每台服务器而不进行并行处理。
-
这听起来像是 Microsoft 的反应式框架 (Rx) 更好的工作。