Parallelism and Entity Framework

Asked

Viewed 264 times

5

I’m having some problems using parallelism (I don’t have much knowledge in this area) with C# and Entity Framework.

My scenario is as follows, I am using an ASP.NET MVC application and within it I have a list of objects that do various validations. As there are many (more than 45,000 on average) if I wait in a single thread, the delay is great.

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

I’m using Parallel.Foreach(list, x => Methododevalidation(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 make validations in parallel? Do you have any articles to recommend?

  • Will this work in the database? Read this: http://answall.com/q/1946/101

  • Ball show @bigown!

1 answer

4

My question is : This is the best way to make validations in parallel?

Not at all. This is one of the worst, I’d say.

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

First of all, a context is not thread-safe. You need to invoke the lock() before trying to validate.

Second, one does not encapsulate a context within a service and the instance multiple times. The collection as a whole needs to be observable. Therefore it is a context only for N validations.

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

  • Thanks Gypsy, is that my scenario today is very complicated... I receive an excel spreadsheet and through it I make 3 validations for each line, that to realize them I need data from the database (usually.

  • You can continue this approach, only you cannot open a context per validation step. Passing context by reference to a function or validation method is the path.

  • OK! Thank you! I will do the performance tests to see what will give =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.