Parallelism and Entity Framework

5

I'm having some problems using parallelism (I'm not very knowledgeable in this area) with C # and Entity Framework.

My scenario is as follows, I'm using an ASP.NET MVC application and inside it I have a list of objects that I do several validations. As there are many (over 45 thousand on average) if I wait in a single thread, the delay is great.

For this I thought of working with parallelism, but I ended up having some problems like dbcontext that I had to instantiate for each thread in order to work on multiple threads.

I'm using Parallel.ForEach (list, x => Validation Method (x) .Wait ()); to perform the validations asynchronously.

Below my validation method.

public Task MetodoDeValidacao(IEnumerable<Lista> lista) {
     return Task.Factory.StartNew(() =>
     {
       if (!_service.fazAlgumaCoisa(lista))
          ModelState.AddModelError("Model", "Você não fez alguma coisa");
     }
}

My question is: Is this the best way to do parallel validations? Do you have any articles to recommend?

    
asked by anonymous 22.12.2015 / 12:55

1 answer

4
  

My question is: Is this the best way to validate in parallel?

Not at all. This is one of the worst I would say.

You are creating the highlighted context problem . This code will never work.

First, a context is not thread-safe . You need to invoke lock() in it before attempting to validate.

Second, you do not encapsulate a context within a service and instantiate it multiple times. The collection as a whole needs to be observable. Therefore it is a context only for N validations.

Instead of using service, use a static class, passing the context reference and locking the context in a critical region when validating.

    
22.12.2015 / 17:33