[英]Share collections between tasks within c# application
I have a wpf application in which I have to fill some Collection : 我有一个wpf应用程序,其中必须填写一些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());
});
}
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. 现在,当多个线程/任务同时调用
Add
方法时,该集合可能变得无效。 For me, it is easier to use thread-safe collections than lock
for example. 对我来说,使用线程安全的集合比使用
lock
更容易。 Also, lock
is quite hard to use when your collection is used by multiple classes. 另外,当您的集合被多个类使用时,
lock
很难使用。
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 . 正如Dave Black在评论中指出的那样,线程安全集合使用无锁同步,这必须比获取锁更快,这可以从MSDN上阅读。
One of the collections you can use is ConcurrentBag<T>
, which can be compared to List<T>
. 您可以使用的集合之一是
ConcurrentBag<T>
,可以将其与List<T>
进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.