I have this code that was running for about 2 hours. After that the program stopped to answer and I paused it in VS and checked on which line it was executing. I stopped in the Parallel statement and said something about “waiting on thread to join and stop sleep”.
It’s obvious that my multithreading experience is small so I have no idea why this happend.
I thought that the thread thats enter the while will be isolated and waiting for all other threads that starts in the foreach.
while (true)
{
Parallel.ForEach(servers, server => // It stopped here
{
Console.WriteLine(string.Format("Checking: {0} Thread: {1}", server.Hostname, Thread.CurrentThread.ManagedThreadId));
try
{
// Do some network stuff
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
});
}
Update 1
Do some network stuff is makeing some UDP sending and receiving with a timeout on 1500 ms. I also have some DB stuff based on Entity Framework here. So it’s probably much that can go wrong. However I still unsure what can cause it. If the sockets (both my UDP stuff and DB stuff) are running and exceed the timeout they will rise an exception that will be “handled”
Isn’t that enough? Can I set some sort of timeout for the complete thread. If it hasn’t joined for 5000 ms kill it?
The “Do some network stuff” would be the first thing I looked at (in particular: is there any chance it can block indefinitely – maybe a
Readwithout timeout on a stream that isn’t sending but isn’t closed). If any of the “Do some network stuff” code blocks, that will block the entireParallel.ForEach, as it doesn’t return from.ForEachuntil every item has completed.Finding the
Parallel.ForEachwaiting on a join is not unexpected (Parallel.ForEachis a split and join, after all) – the important question is: what else is happening, i.e. what are the other threads doing.However, I would also want to ask whether it is possible somebody simply pressed pause on the keyboard (which pauses console output), or had accidentally click-dragged on the console area (which can enter the copy/paste mode, which again pauses console output).