ThreadPool.QueueUserWorkItem with function argument

前端 未结 4 1966
被撕碎了的回忆
被撕碎了的回忆 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 05:59

    Here's a fuller example which gets the result back to the initial thread, and shows how the delegate can be defined anonymously:

    class Program
    {
        static void Main(string[] args)
        {
            using (MultiplyTask task = new MultiplyTask() { Multiplicands = new int[] { 2, 3 } })
            {
                WaitCallback cb = new WaitCallback(delegate(object x)
                {
                    MultiplyTask theTask = x as MultiplyTask;
                    theTask.Result = theTask.Multiplicands[0] * theTask.Multiplicands[1];
                    theTask.Set();
                });
                ThreadPool.QueueUserWorkItem(cb, task);
    
                Console.WriteLine("Calculating...");
                if (task.WaitOne(1000))
                {
                    Console.WriteLine("{0} times {1} equals {2}", task.Multiplicands[0], task.Multiplicands[1], task.Result);
                }
                else
                {
                    Console.WriteLine("Timed out waiting for multiplication task to finish");
                }
            }
        }
    
        private class MultiplyTask : EventWaitHandle
        {
            internal MultiplyTask() : base(false, EventResetMode.ManualReset) { }
            public int[] Multiplicands;
            public int Result;
        }
    }
    
    0 讨论(0)
  • 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 });
    
    0 讨论(0)
  • 2020-12-15 06:07

    In my case, I needed an anonymous function. i.e., write to a stream asynchronously. So I used this:

    ThreadPool.QueueUserWorkItem(state => {
        serializer.Serialize(this.stream);
        this.stream.Flush();
    });
    
    0 讨论(0)
  • 2020-12-15 06:12

    Using a lambda expression would also work

    ThreadPool.QueueUserWorkItem(state => Multiply(2,3));
    
    0 讨论(0)
提交回复
热议问题