Share collections between tasks within c# applicat

2019-09-18 13:49发布

问题:

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());
            });
        }

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?

回答1:

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.

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.

One of the collections you can use is ConcurrentBag<T>, which can be compared to List<T>.