C
C#2w ago
eid

await-work in thread class is different from await-work in task class?

var thread = new Thread(async () => { Console.WriteLine($"Thread before await: {Thread.CurrentThread.ManagedThreadId}"); await Task.Delay(500); // Simulate asynchronous delay Console.WriteLine($"Thread after await: {Thread.CurrentThread.ManagedThreadId}"); }); thread.Start(); thread.Join(); // Wait for the thread to complete // Using Task Task.Run(async () => { Console.WriteLine($"Task before await: {Thread.CurrentThread.ManagedThreadId}"); await Task.Delay(500); // Simulate asynchronous delay Console.WriteLine($"Task after await: {Thread.CurrentThread.ManagedThreadId}"); }).Wait(); // Wait for the task to complete
3 Replies
Denis
Denis2w ago
When you run a task, it doesn't create a new thread. It schedules your given unit of work to be executed without blocking the calling thread. Whether this actually happens or not is up to the .net task scheduler. Using .Wait on a task, afaik, mitigates the whole point of the task and will end up running on the calling thread. When a task completes and returns, it can switch back to the caller context. However, if you do not need this, you can call ConfigureAwait(false) to disable returning to the calling thread context
ffmpeg -i me -f null -
the differences are mainly in the code run before the await (and then eventually ConfigureAwait), but also it depends which differences you care
wasabi
wasabi2w ago
new Thread(async () => also makes no sense. There is no overload of Thread which accepts a Func<Task>