✅ Is it correct to use threads now?
I read in book following:
as soon as you type new Thread(), it`s over; your project already have legacy codebut what about this code: is it correct? how to rewrite it so that it stops being legacy code?
3 Replies
what is meant is that u should not create ur own threads (in most cases - there are valid reasons to as well) but use the thread pool instead.
that is nowadays done buy using asynchronous programming approach around
async
/await
and Task<T>
and usually when dealing with GUI like in ur code example, u would let the UI thread be the main thread and schedule background tasks on the thread pool.
ur code has it vice versaTo confuse you a bit more... even if you at some point need to use
Thread
instead of Task
, then use the ThreadPool
. Creating a new thread using new Thread
is more expensive, while the thread pool provides pre-created threads you can use.
Another important note. Using threads/tasks everywhere is one of the beginner mistakes I made, assuming it will automatically give me extra performance. If logically the operation does not benefit from multiple threads, or running on a background thread, then there is most likely no need to apply these concepts. Thread/task is a hammer, and every part of your code is definitely not a nail.
An example of a beneficial use of tasks, is an IO bound operation. You delegate the work to a background thread, to, e.g., read a file, or even multiple files.
Please correct me if I'm wrongsmth like that?
instead of just thread start
/close