C
C#17mo ago
SWEETPONY

✅ 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 code
but what about this code:
LogForm? _logForm = null;
Thread shower = new Thread(() =>
{
_logForm = new LogFrom(script, variables);
Application.Run(_logForm);
});

shower.Start();

while (_logForm == null)
Task.Delay(50).Wait();
LogForm? _logForm = null;
Thread shower = new Thread(() =>
{
_logForm = new LogFrom(script, variables);
Application.Run(_logForm);
});

shower.Start();

while (_logForm == null)
Task.Delay(50).Wait();
is it correct? how to rewrite it so that it stops being legacy code?
3 Replies
cap5lut
cap5lut17mo ago
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 versa
Denis
Denis17mo ago
To 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 wrong
SWEETPONY
SWEETPONYOP17mo ago
smth like that?
ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod));
ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod));
instead of just thread start /close
Want results from more Discord servers?
Add your server