Alexander Ryan Baggett Alexander Ryan Baggett -4 years ago 78
C# Question

Better way to Parallelize assignments

Now, I am still a bit new to Lambdas, Funcs, Delegates, Actions and so forth, But I am trying to find a better way to Parallelize assignments that depend on database operations. In other words I have a lot of data to pull from a database all in one go, and I would like to do it in Parallel and not in serial.

So far I am using a

in combo with
, but I can't help but wonder if there is a more elegant way to do this. I had tried Parallel.Invoke, but I couldn't call Invoke() on a Lambda expression (maybe there is no func literal?). Apparently it has to be assigned to a Func first before you can call Invoke() and then treat it as an Action.

This is what I have so far.

List<Func<Object>> Assignments = new List<Func<object>>();
Assignments.Add( () => lookups.Acknowledgements = DBRepository.GetAll<Acknowledgement>());
Assignments.Add( () => lookups.AcknowledgementDetails = DBRepository.GetAll<AcknowledgementDetail>());
Assignments.Add( () => lookups.AcknowledgementRadioButtons = DBRepository.GetAll<AcknowledgementRadioButtonSection>());
Assignments.Add( () => lookups.AcknowledgementRadionButtonItems = DBRepository.GetAll<AcknowledgementRadioButtonSectionItem>());
Assignments.Add( () => lookups.AcknowledgementTextBoxes = DBRepository.GetAll<AcknowledgementTextBoxSection>());
Assignments.Add( () => lookups.MarketingPages = DBRepository.GetAll<MarketingPage>());
Assignments.Add( () => lookups.MarketingPageDetails = DBRepository.GetAll<MarketingPage_Detail>());
// and many many more...
Parallel.ForEach(Assignments, (assignement) =>


Is there a prettier, more elegant or otherwise better way to parallelize assignment operations in general?

Answer Source

You can still use Parallel.Invoke to save some lines:

    () => lookups.Acknowledgements = DBRepository.GetAll<Acknowledgement>(),
    () => lookups.AcknowledgementDetails = DBRepository.GetAll<AcknowledgementDetail>()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download