C# - ThreadPool QueueUserWorkItem Use?

前端 未结 4 843
星月不相逢
星月不相逢 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:12

    I'm not entirely sure what kind of syntax you're looking for, but if you don't like the unused a in your example, why not use Task instead?

    Task.Run(() => doStuff("hello world"));
    

    It doesn't really seem a lot better, but at least it doesn't have an unused identifier.

    Note: Task.Run() is .Net 4.5 or later. If you're using .Net 4 you have to do:

    Task.Factory.StartNew(() => doStuff("hello world"));
    

    which isn't as short.

    Both of the above do use the thread pool.

    If you really must avoid using a lambda, you can use an anonymous delegate (which @nowhewhomustnotbenamed already mentioned):

    Task.Run(delegate { doStuff("Hello, World!"); });
    

    But what's the point of that? It's much less readable!

提交回复
热议问题