For循环C#上的多线程

MultiThread on For Loop C#

我正在制作一个程序来检查我公司服务器的状态。 我的服务器信息将加载到 DgvServer 我使用 for 循环来检查服务器的状态:

    private void btnCheck_Click(object sender, EventArgs e)
    {
        try
        {
            string ip = "";
            Ping ping = new System.Net.NetworkInformation.Ping();
            PingReply pingreplay = null;
            for (int i = 0; i < dgvServer.Rows.Count; i++)
            {
                //Get IP address
                ip = dgvServer.Rows[i].Cells[1].Value.ToString();
                pingreplay = ping.Send(ip,10000);
                if (pingreplay.Status == IPStatus.Success)
                {
                    //update status of server
                    dgvServer.Rows[i].Cells[4].Value = "Online";
                }
                else
                   //Update status of server
                    dgvServer.Rows[i].Cells[4].Value = "Offline";
            }
        }
        catch(Exception ex)
            {
                MessageBox.show(ex.Message);
            }
    }

如果所有服务器都在线就可以,但是如果某些服务器离线,这段代码需要很长时间才能完成。所以,我想为每个循环使用一个线程来检查每个服务器的状态。我不使用并行,因为这是 .net 2.0 程序。 请给我一些使用线程改进此代码的建议。 非常感谢!

尝试Parallel.For或Parallel.For每个。

查看此link了解更多信息https://msdn.microsoft.com/en-us/library/dd460713(v=vs.110).aspx

这是 Parallel.For 与 .NET 2.0

一起使用的绝妙实现

In this article we will see a way to implement a static For method in C#2.0 having the same behavior.

https://dotnetgalactics.wordpress.com/2009/11/19/how-to-provide-a-parallel-for-loop-in-c2-0-2/

您可以使用文章中提供的方法,使用 Parallel.For 循环并行轮询所有服务器。

请注意,只要最长的单个服务器检查需要,这仍然会阻止 UI。

要考虑的另一个选择是将该代码块放入 BackgroundWorker,这样 UI 就不会被阻塞。

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

您可以为每个服务器创建一个 BackgroundWorker 以进行更新,允许每个服务器的状态在收到回复后立即在网格中更新,或者您可以只创建一个 BackgroundWorker(可能使用 Parallel.For上面的实现)。