在 C# 应用程序中的任务之间共享 collections
Share collections between tasks within c# application
我有一个 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());
});
}
问题是我调用这个方法后 collections 仍然是空的。当我像这样更改方法时(同步方式):
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());
}
collections变满了!!所以我需要知道 :
如何在不同的任务之间共享 collections?
我建议使用 collection,即 thread-safe,而不是锁定。现在,当多个线程/任务同时调用 Add
方法时,collection 可能会失效。例如,对我来说,使用 thread-safe collection 比 lock
更容易。此外,当您的 collection 被多个 类 使用时,lock
很难使用。
如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.
您可以使用的 collection 之一是 ConcurrentBag<T>
,它可以与 List<T>
.
进行比较
我有一个 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());
});
}
问题是我调用这个方法后 collections 仍然是空的。当我像这样更改方法时(同步方式):
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());
}
collections变满了!!所以我需要知道 :
如何在不同的任务之间共享 collections?
我建议使用 collection,即 thread-safe,而不是锁定。现在,当多个线程/任务同时调用 Add
方法时,collection 可能会失效。例如,对我来说,使用 thread-safe collection 比 lock
更容易。此外,当您的 collection 被多个 类 使用时,lock
很难使用。
如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.
您可以使用的 collection 之一是 ConcurrentBag<T>
,它可以与 List<T>
.