在C#中,有几种方式可以使用多线程:
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread thread = new Thread(DoWork);
thread.Start();
// 继续执行主线程的其他操作
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);
// 继续执行主线程的其他操作
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();
// 继续执行主线程的其他操作
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#中使用多线程的几种常见方式。根据实际需求,选择适合的方式来处理多线程任务。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: c#中tcplistener的用法是什么