I’m attempting to use the QueueUserWorkItem method on ThreadPool, however, I’m having some problems when I attempt to pass a delegate to the method. I imagine the problem with my code lies in the way I’ve setup my delegate, but I can’t seem to figure it out, even after searching around on google.
I’m creating my delegate like so:
public delegate void GetLatencyDelegate(Server server);
I’m attempting to loop through a list of servers and run the servers GetLatency method. Each time I loop through to a new server, a new thread should be ran from the pool to run the GetLatency method. The idea is that this should speed up the process. My code for this is the following:
ThreadPool.SetMaxThreads(50, 50);
foreach (Server server in serverList)
{
GetLatencyDelegate gld = new GetLatencyDelegate(server.GetLatency);
ThreadPool.QueueUserWorkItem(new WaitCallback(gld));
}
However, I get two errors. One being:
“No overload for ‘GetLatencyDelegate’ matches delegate
‘System.Threading.WaitCallback’
The other being:
‘No overload for ‘GetLatency’ matches delegate
‘Program.GetLatencyDelegate’
The first error occurs because the signature for
WaitCallbackis not the same as the signature forGetLatencyDelegate. The two should be identical.The second error occurs because
Server.GetLatencyalso does not have a signature compatible withGetLatencyDelegate: the former accepts no parameters, while the latter expects theServerinstance to be passed in.In fact there is absolutely no need to define
GetLatencyDelegatein the first place. You can simply provide a lambda with a signature compatible withWaitCallback: