并行性和异步是在 C# 中处理并发任务的重要概念。下面给出一些使用并行性和异步的代码示例的解决方法。
Parallel.ForEach(collection, item =>
{
// 并行处理每个集合项
// ...
});
var result = collection.AsParallel()
.Where(item => item.SomeCondition)
.Select(item => item.SomeProperty)
.ToList();
public async Task MyMethodAsync()
{
// 异步操作
await Task.Delay(1000);
return 42;
}
var tasks = new List>();
for (int i = 0; i < 10; i++)
{
int index = i; // 避免闭包问题
tasks.Add(Task.Run(() =>
{
// 并行处理每个任务
return SomeLongRunningOperation(index);
}));
}
await Task.WhenAll(tasks);
await Task.Run(() =>
{
Parallel.ForEach(collection, async item =>
{
// 并行异步处理每个集合项
await SomeAsyncOperation(item);
});
});
这些示例展示了在 C# 中使用并行性和异步的一些常见模式。使用并行性和异步可以提高程序的性能和响应能力,但在设计时需要注意线程安全和资源竞争的问题。