Many individual threads run from one method
Hello,
At the moment I am developing an app in VC# 2008. The aim is to ping a large number of ip addresses simultaneously.
Basically, I generate a list of 20 IP addresses and make a new thread to ping them. Then I clear the list, generate another 20, and make another thread. At any one time, I may have 20 threads all pinging, making callbacks to the main thread.
However, the issue I'm having is that the threads appear to be sharing the same variables, even though they are started individually, since I am getting the error "Collection was modified; enumeration operation may not execute." Other times the entire app just exits spontaneously without error.
I'm relatively new to threading and have searched the forums without success.
Here is my code:
private void MakePingThreads()
{
//Calculate range of IPs here and put them in the list Next20IPs
while(ipcounter < 5)
{ // Ping them all 5 times
ThreadStart PingerThreadstart = delegate { PingList(Next20IPs); };
new Thread(PingerThreadstart).Start();
Next20IPs.Clear();
ipcounter = 0;
}
}
private void PingList(List<IPAddress> IpList)
{
ProcessStatus ProcessStatusCall = new ProcessStatus(UpdateResponse);
foreach (IPAddress IpAddress in IPList) //<-- Error here
{
Ping Packet = new Ping();
PingReply Reply = Packet.Send(IpAddress, 1000);
if (this.IsDisposed == false) // Check there is still a thread to respond to
{
this.Invoke(ProcessStatusCall, new object[] { IpAddress.ToString(), Reply.Status });
}
else
{
return;
}
}
}
private delegate void ProcessStatus(string Message, IPStatus IPInfo);
private void UpdateResponse(string Message, IPStatus IPInfo)
{
if (IPInfo == IPStatus.Success)
{
txtReply.Text += Message;
txtReply.Text += " Success";
}
//else if (IPInfo == IPStatus.TimedOut)
//{
// txtReply.Text += " Timeout";
//}
txtReply.Text += "\r\n";
}
Thankyou.
Re: Many individual threads run from one method
If you want threads to share the same object, use the lock statement
Re: Many individual threads run from one method
Code:
private void MakePingThreads()
{
ThreadStart PingerThreadstart = delegate {
for (int i = 0; i < 5; i++)
PingList(Next20IPs);
};
}
In your original code Next20IPs could be cleared before any thread actually ran, probably not what you wanted.
Re: Many individual threads run from one method
Quote:
Originally Posted by
Talikag
thankyou for the link.
However, it's not so much that I want them to share the same object, I want each thread to each have their own, individual List of IP addresses, and be totally independent threads (ie no sharing of information), and only send back information about successful pings to the main thread.
I think I may not be starting the threads correctly. I more or less want to start the thread, give it the list of IP addresses, and let it ping them, without the list being linked back or modified by the main thread or any other threads. (I hope this makes sense)