1

I have a very strange problem with my code. It will fully run the 1st for loop, then complete the foreach, but then it will skip back to the "ThreadStart IMAPDelegate" (line 1 of the for loop) and then crash because of an ArgumentOutOfRangeException. Can someone explain why the program is doing this? I debugged it line by line and it literally just skips back up into the a line in the for loop. If it had normally run the for loop again, it would have set x back to 0 and it would not have crashed. Any suggestions?

for (int x = 0; x < UserInfo.Count; x++)
{
    ThreadStart IMAPDelegate = delegate{SendParams(UserInfo[x], IMAPServers[x]); };
    MyThreads.Add(new Thread(IMAPDelegate));
}

foreach (Thread thread in MyThreads)
{
    thread.Start();
}

1 Answer 1

5

This is by design when you use an anonymous method like that. As soon as the thread starts running, it executes the SendParams() method call. Which then bombs because the "x" variable is already incremented beyond UserInfo.Count. Fix:

for (int x = 0; x < UserInfo.Count; x++)
{
    int user = x;
    ThreadStart IMAPDelegate = delegate{SendParams(UserInfo[user], IMAPServers[user]); };
    MyThreads.Add(new Thread(IMAPDelegate));
}
Sign up to request clarification or add additional context in comments.

10 Comments

+1 Otherwise know as "Closing Over the Loop Variable":(blogs.msdn.com/b/ericlippert/archive/2009/11/12/….
When when UserInfo and MyTheads both have more than 1 element, it gives me the error. Count = Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation.
That's not an error, just the debugger complaining that it temporarily lost its marbles. That happens. There's a hotfix for debugger problems with threads when you use VS2008. Or press F5. support.microsoft.com/kb/957912
Now only the 1st thread in the array will start, all others will not.
Hmya, threads don't just refuse to start when you call their Start() method. I'm going to guess that anonymous methods really confuse the stuffing out of you. There's no compelling reason to use them here, this will work just as well when you use a little private helper method as the ThreadStart delegate target.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.