在C#中,可以使用多種方法來實現多線程。以下是一些常見的方法:
System.Threading.Thread
類創建線程:using System;
using System.Threading;
class Program
{
static void Main()
{
Thread t = new Thread(new ThreadStart(MyMethod));
t.Start();
}
static void MyMethod()
{
Console.WriteLine("Running on a separate thread.");
}
}
Task
類(推薦):using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
await Task.Run(() => MyMethod());
}
static void MyMethod()
{
Console.WriteLine("Running on a separate thread.");
}
}
Parallel
類進行并行循環:using System;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Parallel.For(0, 10, i =>
{
Console.WriteLine($"Running iteration {i} on a separate thread.");
});
}
}
ThreadPool
類:using System;
using System.Threading;
class Program
{
static void Main()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod));
}
static void MyMethod(object state)
{
Console.WriteLine("Running on a separate thread.");
}
}
這些方法都可以用于實現多線程。但是,使用Task
類通常是最佳選擇,因為它提供了更好的性能和更簡單的錯誤處理。