c#多线程相关类和方法的示例代码和实例实现
时间: 2024-02-17 14:02:07 浏览: 82
下面是C#多线程相关类和方法的示例代码和实例实现:
1. Thread类示例:
```csharp
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(new ThreadStart(Worker));
thread.Start();
Console.WriteLine("Main thread is running.");
thread.Join(); // 等待子线程结束
Console.WriteLine("Main thread is done.");
}
static void Worker()
{
Console.WriteLine("Worker thread is running.");
Thread.Sleep(3000); // 模拟耗时操作
Console.WriteLine("Worker thread is done.");
}
}
```
2. ThreadPool类示例:
```csharp
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(Worker));
Console.WriteLine("Main thread is running.");
Console.ReadLine();
}
static void Worker(object state)
{
Console.WriteLine("Worker thread is running.");
Thread.Sleep(3000); // 模拟耗时操作
Console.WriteLine("Worker thread is done.");
}
}
```
3. Task类示例:
```csharp
using System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
Task task = Task.Run(() =>
{
Console.WriteLine("Worker task is running.");
Thread.Sleep(3000); // 模拟耗时操作
Console.WriteLine("Worker task is done.");
});
Console.WriteLine("Main thread is running.");
task.Wait(); // 等待任务结束
Console.WriteLine("Main thread is done.");
}
}
```
4. Parallel类示例:
```csharp
using System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
Parallel.For(0, 10, i =>
{
Console.WriteLine("Worker task {0} is running.", i);
Thread.Sleep(1000); // 模拟耗时操作
Console.WriteLine("Worker task {0} is done.", i);
});
Console.WriteLine("Main thread is running.");
Console.ReadLine();
}
}
```
注意:这些示例代码只是演示了如何使用多线程相关类和方法,实际应用中还需要考虑线程安全、异常处理等问题。
阅读全文