在C#应用程序的任务之间共享收藏 [英] Share collections between tasks within c# application
问题描述
我有,我有,以填补一些收藏WPF应用程序:
I have a wpf application in which I have to fill some Collection :
private async Task FillList()
{
await Task.Factory.StartNew(() =>
{
gdpList = SimpleIoc.Default.GetInstance<ICrud<gdp_groupe>>().GetAll().ToList();
MedecinGDP.AddRange(SimpleIoc.Default.GetInstance<ICrud<vue_medecin>>().GetAll());
CodeGDP_Collection.AddRange(gdpList);
FiltredParticipant.AddRange(SimpleIoc.Default.GetInstance<ICrud<fsign_fiche>>().GetAll());
});
}
问题是,集合仍然为空后,我调用此方法。当我改变这样的(synchrounous方式)的方式:
The problem is that the collections still empty after I call this method. when I change the method like this (synchrounous way):
private void FillList()
{
gdpList = SimpleIoc.Default.GetInstance<ICrud<gdp_groupe>>().GetAll().ToList();
MedecinGDP.AddRange(SimpleIoc.Default.GetInstance<ICrud<vue_medecin>>().GetAll());
CodeGDP_Collection.AddRange(gdpList);
FiltredParticipant.AddRange(SimpleIoc.Default.GetInstance<ICrud<fsign_fiche>>().GetAll());
}
集合变得充满!所以,我需要知道:
the collections become filled!! So I need to know :
我如何不同的任务之间共享收藏?
How can I share collections between different tasks?
推荐答案
而不是锁定的,我会建议使用一个集合,是线程安全的。现在,当在同一时间添加
方法由多个线程/任务调用,收集可以变得无效。对我来说,它更容易使用比锁定
例如线程安全的集合。此外,锁定
是相当难用,当你收集使用多个类。
Instead of locking, I would advise to use a collection that is thread-safe. Now, when at the same time the Add
method is called by multiple threads / tasks, the collection can become invalid. For me, it is easier to use thread-safe collections than lock
for example. Also, lock
is quite hard to use when your collection is used by multiple classes.
由于戴夫黑色在评论中指出的,线程安全的集合使用无锁同步这是必须快于采取锁,你可以阅读 MSDN 。
As Dave Black pointed out in a comment, the thread-safe collections use lock-free synchronization which is must faster than taking a lock, as you can read on MSDN.
一,你可以使用收藏的是 ConcurrentBag&LT; T&GT;
,它可以比作列表&LT; T&GT;
One of the collections you can use is ConcurrentBag<T>
, which can be compared to List<T>
.
这篇关于在C#应用程序的任务之间共享收藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!