Which code is preferable? [closed]
A:
new Thread(new ThreadStart(ListenForResponse)) { IsBackground = true }.Start();
B:
ThreadStart threadStart = new ThreadStart(ListenForResponse);
Thread listeningThread = new Thread(threadStart);
listeningThread.IsBackground = true;
listeningThread.Start();
As far as I can tell they are functionally equivalent. I'm just wondering which is preferred. Which would you rather see in a project?
I prefer this:
Thread listeningThread = new Thread(new ThreadStart(ListenForResponse))
{
IsBackground = true
}
listeningThread.Start();
This question is quite subjective, though.
If you are setting more parameters on the various objects, the one-liner version starts to get hard to read.
On the other hand, writing everything out explicitly for the simple case can be wordy and clutter the meaning of what's going on.
Also, a personal pet peeve is putting a function call waaay at the end of the line, where it is hard to see, as in your first example.
Even if you want to use that syntax, I would prefer to see the .Start()
on its own line.
I personally prefer the selection B. It is a lot more readable. Each step is logically laid out, you can understand what is happening by simply stepping through it.
My opinion of A is that its showoff code. You do this to show how short you can make an operation, but its re-usability is pretty low and requires you understand the structure of the call a little better.
My opinion: Assume your code will be used by someone else and assume they need all the help they can get. Choose the most readable solution that does not sacrifice efficiency.
精彩评论