Parallel.ForEach 添加到列表 [英] Parallel.ForEach with adding to list
本文介绍了Parallel.ForEach 添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试运行多个连接到远程站点(通过网络)并返回通用列表的函数.但我想同时运行它们.
I'm trying to run multiple functions that connect to a remote site (by network) and return a generic list. But I want to run them simultaneously.
例如:
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;
}
在我看来,对结果"的多次插入可能同时发生......这可能会导致我的应用程序崩溃.
As I see it, multiple insertions to 'results' may happend at the same time... Which may crash my application.
我怎样才能避免这种情况?
How can I avoid this?
推荐答案
//In the class scope:
Object lockMe = new Object();
//In the function
lock (lockMe)
{
results.AddRange(tmpResults);
}
基本上一个锁意味着只有一个线程可以同时访问那个临界区.
Basically a lock means that only one thread can have access to that critical section at the same time.
这篇关于Parallel.ForEach 添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文