C# 新线程中的start方法
我有一个方法C# 新线程中的start方法,c#,multithreading,.net-3.5,C#,Multithreading,.net 3.5,我有一个方法PatchUpdates,它调用CheckConnection方法来检查与远程pc的连接如果为真,那么它将返回到用户界面的第一个方法并执行一些其他操作 我搜索并发现我需要使用线程,所以我正在创建新的线程 但我的应用程序挂起并停止,什么也没发生 请问我做错了什么 谢谢 public void PatchUpdates() { try { foreach (DataGridVi
PatchUpdates
,它调用CheckConnection
方法来检查与远程pc的连接如果为真,那么它将返回到用户界面的第一个方法并执行一些其他操作
我搜索并发现我需要使用线程,所以我正在创建新的线程
但我的应用程序挂起并停止,什么也没发生
请问我做错了什么
谢谢
public void PatchUpdates()
{
try
{
foreach (DataGridViewRow OfficeListRow in DGV_OfficeList.Rows)
{
string vIPAddress;
string vSoruceFilePath;
int RowNum;
foreach (DataGridViewRow FileListRow in DGV_FileList.Rows)
{
Thread thrd = new Thread(new System.Threading.ThreadStart(PatchUpdates));
thrd.Start();
vIPAddress = OfficeListRow.Cells[1].Value.ToString();
vSoruceFilePath = FileListRow.Cells[4].Value.ToString();
RowNum = OfficeListRow.Index;
///Check the connection to pc
if (CheckConnection(vIPAddress) == true)
{
//MessageBox.Show(vIPAddress + " Pingable ");
DGV_OfficeList[2, RowNum].Value = "Online";
OfficeListRow.DefaultCellStyle.BackColor = Color.LightGreen;
}
else
{
//MessageBox.Show(vIPAddress + " Not Pingable ");
DGV_OfficeList[2, RowNum].Value = "Offline";
OfficeListRow.DefaultCellStyle.BackColor = Color.LightCyan;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public static bool CheckConnection(string IPAddress)
{
bool vPingable = false;
try
{
Ping png = new Ping();
PingReply PngReply = png.Send(IPAddress);
vPingable = PngReply.Status == IPStatus.Success;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
return vPingable;
}
您正在通过
PatchUpdates()
方法将PatchUpdates
传递给ThreadStart委托
Thread thrd = new Thread(new System.Threading.ThreadStart(PatchUpdates));
thrd.Start();
这意味着PatchUpdates()
方法在新的第二个线程上重新启动,在新的第三个线程上重新启动,在新的第四个线程上重新启动,依此类推
基本上,您正在启动无限多个新线程(只要
DGV_FileList.Rows
中有项目),这将最终消耗您的所有资源。使用异步Ping,以便您可以在同一个sime上执行多个Ping。在thrd.Start()上设置断点代码>运行代码。你击中断点多少次?你认为这是为什么?