C# TPL 应用demo
时间: 2023-07-12 14:25:02 浏览: 65
以下是一个简单的基于 TPL 的 C# 应用程序示例,它使用 Parallel.ForEach 方法并行处理一个字符串列表:
```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program {
static void Main(string[] args) {
List<string> list = new List<string> {
"apple",
"banana",
"cherry",
"date",
"elderberry",
"fig",
"grape"
};
Parallel.ForEach(list, item => {
Console.WriteLine($"Processing item '{item}' on thread {Task.CurrentId}");
// 模拟处理时间
Task.Delay(1000).Wait();
});
Console.WriteLine("All items processed");
}
}
```
在上面的示例中,我们首先创建了一个字符串列表 `list`,其中包含七个元素。然后,我们使用 `Parallel.ForEach` 方法对列表中的每个元素进行并行处理。在处理每个元素时,我们将元素的名称和当前线程的 ID 打印到控制台上,并使用 `Task.Delay` 方法模拟处理时间。最后,我们打印一条消息,表示所有元素都已处理完毕。
在运行上面的示例时,您应该会看到类似于以下输出:
```
Processing item 'banana' on thread 3
Processing item 'apple' on thread 1
Processing item 'cherry' on thread 2
Processing item 'elderberry' on thread 4
Processing item 'fig' on thread 5
Processing item 'date' on thread 6
Processing item 'grape' on thread 7
All items processed
```
可以看到,所有元素都在不同的线程上并行处理,处理时间也得到了模拟。请注意,由于 `Parallel.ForEach` 方法是异步的,因此程序可能会在所有元素都处理完毕之前结束。如果您希望等待所有任务完成后再继续执行程序,请使用 `Task.WaitAll` 方法等待所有任务完成。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)