C# - ThreadPool QueueUserWorkItem Use?

前端 未结 4 768
星月不相逢
星月不相逢 2020-12-24 12:39

Just right now I\'m using following code to add queued threads. I don\'t like it. And my colleagues won\'t either because they don\'t know C# very well. All I want is of cou

4条回答
  •  生来不讨喜
    2020-12-24 13:06

    What about this?

    class Program
    {
        static void Main(string[] args)
        {
            ThreadPool.QueueUserWorkItem(MyWork, "text");
            Console.ReadKey();
        }
    
        private static void MyWork(object argument)
        {
            Console.WriteLine("Argument: " + argument);
        }
    }
    

    Or if you do not want to be signature restrictive and have a simple way of putting methods on a thread you can do it like this.For methods that do and do not return a value and have up to 6 parameters it would require you to define 12 overloads if I am not mistaken. It requires a bit more work up front, but is more simple to use.

    class Program
    {
        static void Main(string[] args)
        {
            var myClass = new MyClass();
            myClass.DoWork();
            Console.ReadKey();
        }
    }
    
    public static class ObjectThreadExtension
    {
        public static void OnThread(this object @object, Action action)
        {
            ThreadPool.QueueUserWorkItem(state =>
            {
                action();
            });
        }
    
        public static void OnThread(this object @object, Action action, T argument)
        {
            ThreadPool.QueueUserWorkItem(state =>
            {
                action(argument);
            });
        }
    }
    
    public class MyClass
    {
        private void MyMethod()
        {
            Console.WriteLine("I could have been put on a thread if you like.");
        }
    
        private void MySecondMethod(string argument)
        {
            Console.WriteLine(argument);
        }
    
        public void DoWork()
        {
            this.OnThread(MyMethod);
            this.OnThread(MySecondMethod, "My argument");
        }
    }
    

提交回复
热议问题