Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadPool.QueueUserWorkItem with function argument

Tags:

c#

I am using C# 2.0 and want to call a method with a couple of parameters with the help of ThreadPool.QueueUserWorkItem, so I tried as follows:

ThreadPool.QueueUserWorkItem(new WaitCallback(Multiply(2, 3)));

private int Multiply(int x,int y)
{
  int z=(x*y);
  return z;
}

I am getting compilation error. So please guide me, how can I call a function with multiple arguments with ThreadPool.QueueUserWorkItem?.

I have another query that when I am using ThreadPool.QueueUserWorkItem then how to use here anonymous function as a result I can write the code there instead of calling another function. If it is possible in C# v2.0 then please guide me with code.

like image 469
Thomas Avatar asked Sep 09 '25 16:09

Thomas


1 Answers

You should declare a method which have the same definition as WaitCallback delegate. You can use the following code snippet:

ThreadPool.QueueUserWorkItem(Multiply, new object[] { 2, 3 }); 

public static void Multiply(object state)
{
    object[] array = state as object[];
    int x = Convert.ToInt32(array[0]);
    int y = Convert.ToInt32(array[1]);
}

Anonymous delegate version is:

 ThreadPool.QueueUserWorkItem(delegate(object state)
    {
        object[] array = state as object[];
        int x = Convert.ToInt32(array[0]);
        int y = Convert.ToInt32(array[1]);
    }
    , new object[] { 2, 3 });
like image 161
Svetlin Ralchev Avatar answered Sep 12 '25 07:09

Svetlin Ralchev