Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - ThreadPool QueueUserWorkItem Use?

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 course to queue a method to be executed in a new thread.

private static void doStuff(string parameter) {     // does stuff }  // call (a) ThreadPool.QueueUserWorkItem(a => doStuff("hello world")); // call (b) ThreadPool.QueueUserWorkItem(delegate { doStuff("hello world"); }); 

So are there other use variations of ThreadPool.QueueUserWorkItem ?

Best would be another 1-Line-Call. If possible with use of Func<> or Action<>.


EDIT: Got (b) from the answers and comments and I like it better already.
like image 801
Bitterblue Avatar asked Jul 02 '13 07:07

Bitterblue


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

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!

like image 73
Matthew Watson Avatar answered Sep 19 '22 19:09

Matthew Watson