43 ms·
I concur, with a caveat - feel free to use threading / async I/O if you think you really understand the runtime behaviour of your code. I've seen so much code
by ro_sharp 10y ago
I concur, with a caveat - feel free to use threading / async I/O if you think you really understand the runtime behaviour of your code.
I've seen so much code that just runs TaskFactory.StartNew some arbitrary number of times in a loop to run some CPU intensive task with no/effectively no I/O, presupposing a performance improvement as a result.
Understand runtime performance. Understand the different failure modes inherent in multi-threaded approaches, and lastly: test, profile, test and profile again!
- thomasz 10y agoIs there something wrong with for(int i = 0; i < Environment.ProcessorCount; i++) Task.Factory.StartNew(...); ?
- quinnftw 10y agoPotentially, yes. Assuming that you are correctly synchronizing the actions inside each Task as to avoid race conditions (a big assumption), there is no control on the number of threads here. What if your program is already using a bunch of threads for something else, and then you go ahead and spawn off 10 more? You will oversaturate the CPU and end up with virtual threads, thus incurring scheduling overhead. In my opinion when you are doing this type of thing you should almost always use a thread pool to ensure that you aren't creating an unreasonable number of threads.
- mdpopescu 10y agoFor one thing, prefer Task.Run to Task.Factory.StartNew - see https://blogs.msdn.microsoft.com/pfxteam/2011/10/24/task-run-vs-task-factory-startnew/ https://blogs.msdn.microsoft.com/pfxteam/2011/10/24/task-run...
- flukus 10y ago> and lastly: test, profile, test and profile again! This, this and this. I see so much code where threading and caching are thrown around as a solution to a performance and no one ever tests to see if it's actually an improvement. I saw one the other day that used multiple threads to call a micro service which locked execution to a single caller and most of the bottleneck was serialization/deserialization. Making the microservice a library would have been much more performant.