ThreadPool.QueueUserWorkItem with function argument

前端 未结 4 1973
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 05:18

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:

Th         


        
4条回答
  •  清歌不尽
    2020-12-15 06:04

    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 });
    

提交回复
热议问题