gpt4 book ai didi

c# - Parallel.ForEach 添加到列表

转载 作者:IT王子 更新时间:2023-10-29 03:42:37 24 4
gpt4 key购买 nike

我正在尝试运行多个连接到远程站点(通过网络)并返回通用列表的函数。但我想同时运行它们。

例如:

public static List<SearchResult> Search(string title)
{
//Initialize a new temp list to hold all search results
List<SearchResult> results = new List<SearchResult>();

//Loop all providers simultaneously
Parallel.ForEach(Providers, currentProvider =>
{
List<SearchResult> tmpResults = currentProvider.SearchTitle((title));

//Add results from current provider
results.AddRange(tmpResults);
});

//Return all combined results
return results;
}

在我看来,多次插入“结果”可能会同时发生……这可能会使我的应用程序崩溃。

我怎样才能避免这种情况?

最佳答案

您可以使用 concurrent collection .

The System.Collections.Concurrent namespace provides several thread-safe collection classes that should be used in place of the corresponding types in the System.Collections and System.Collections.Generic namespaces whenever multiple threads are accessing the collection concurrently.

例如,您可以使用 ConcurrentBag因为您无法保证将添加项目的顺序。

Represents a thread-safe, unordered collection of objects.

关于c# - Parallel.ForEach 添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8001748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com