在C#中,有幾種方式可以使用多線程:
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread thread = new Thread(DoWork);
thread.Start();
// 繼續(xù)執(zhí)行主線程的其他操作
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Main thread: " + i);
Thread.Sleep(1000);
}
}
static void DoWork()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Worker thread: " + i);
Thread.Sleep(1000);
}
}
}
using System;
using System.Threading;
class Program
{
static void Main()
{
ThreadPool.QueueUserWorkItem(DoWork);
// 繼續(xù)執(zhí)行主線程的其他操作
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Main thread: " + i);
Thread.Sleep(1000);
}
}
static void DoWork(object state)
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Worker thread: " + i);
Thread.Sleep(1000);
}
}
}
using System;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Task task = Task.Run(DoWork);
task.Wait();
// 繼續(xù)執(zhí)行主線程的其他操作
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Main thread: " + i);
Task.Delay(1000).Wait();
}
}
static void DoWork()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Worker thread: " + i);
Task.Delay(1000).Wait();
}
}
}
這些是C#中使用多線程的幾種常見方式。根據(jù)實際需求,選擇適合的方式來處理多線程任務(wù)。