Junior — Middle
Is it possible to run a separate thread to perform a task?
sobes.tech AI
Answer from AI
Yes, in C# you can run a separate thread to perform a task. There are several ways to do this:
- Thread class:
using System.Threading;
Thread thread = new Thread(() => {
// task code
Console.WriteLine("Running in a separate thread");
});
thread.Start();
- Thread pool via ThreadPool:
ThreadPool.QueueUserWorkItem(_ => {
// task code
});
- Asynchronous tasks with Task:
using System.Threading.Tasks;
Task.Run(() => {
// task code
});
It is recommended to use Task and async/await for convenience and better integration with modern code.