In my program, we split up a large amount of data that needs to be looked over across four threads.
Thread one = new Thread(delegate() { NewMethod(recordsSplitIntoQuarters[0], param2, param3, param4, param5); });
Thread two = new Thread(delegate() { NewMethod(recordsSplitIntoQuarters[1], param2, param3, param4, param5); });
Thread three = new Thread(delegate() { NewMethod(recordsSplitIntoQuarters[2], param2, param3, param4, param5); });
Thread four= new Thread(delegate() { NewMethod(recordsSplitIntoQuarters[3], param2, param3, param4, param5); });
Our coding standards require that we are StyleCop compliant, as it were, and StyleCop demands the following:
SA1410: Remove the parenthesis from the anonymous method, since the delegate's parameter list is empty.
Doing that gives me this compiler error:
The call is ambiguous between the following methods or properties: 'System.Threading.Thread.Thread(System.Threading.ParameterizedThreadStart)' and 'System.Threading.Thread.Thread(System.Threading.ThreadStart)'
I've looked into the ThreadStart and ParameterizedThreadStart objects and I just can't figure out how to get what I need done with either of those objects.
My question: how do the anonymous delegates work? What do they compile down to? In the end, I will have to get this working without the anonymous delegates, but I don't know where to begin.
Thanks for the help,
Seeker
You have two options:
new ThreadStart(delegate { ... })
An anonymous method without parentheses (delegate { ... }
) has an implicit parameter list. The compiler will give it whatever parameters are needed to match the delegate it's being used as. (Your code cannot see the parameters)
This is very useful when writing anonymous event handlers that don't use their parameters; it saves you from typing delegate(object sender, EventArgs e) { ... }
.
However, when calling the Thread
constructor, there are two different overloads that take two kinds of delegates.
The compiler has no way of knowing which delegate type you're trying to create, since you didn't specify a parameter list.