Junior — Middle
È possibile avviare un thread separato per eseguire un compito?
sobes.tech AI
Risposta dell'AI
Sì, in C# è possibile avviare un thread separato per eseguire un compito. Ci sono diversi metodi:
- Classe Thread:
using System.Threading;
Thread thread = new Thread(() => {
// codice del compito
Console.WriteLine("Eseguito in un thread separato");
});
thread.Start();
- Pool di thread tramite ThreadPool:
ThreadPool.QueueUserWorkItem(_ => {
// codice del compito
});
- Task asincroni con Task:
using System.Threading.Tasks;
Task.Run(() => {
// codice del compito
});
Si consiglia di usare Task e async/await per maggiore comodità e migliore integrazione con il codice moderno.