Sobes.tech
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:

  1. Classe Thread:
using System.Threading;

Thread thread = new Thread(() => {
    // codice del compito
    Console.WriteLine("Eseguito in un thread separato");
});
thread.Start();
  1. Pool di thread tramite ThreadPool:
ThreadPool.QueueUserWorkItem(_ => {
    // codice del compito
});
  1. 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.