I need to insert some data and I’m doing it by calling WCF from my UI and passing a list of objects. Then the service calls a lower business layer which inserts sequentialy the items (calling several other managers and making a lots of call/insert throught ObjectContext)
Now the problem I can’t understand is this:
-
If I call the service more times and passing items one by one everything works fine, inserts goes in parallel and I get some performance benefit concerning time.
-
If I try to call a parallel foreach in the service class I got an exeception, because ObjectContext is it not thread-safe, but I can’t lock code every time I use it because it happens too many time
Why if I call WCF does it work? Is there a way to do the same in my manager class?
Thank you
Depending on your service configuration a new instance is created for every parallel service-call. But using a parallel loop within the service will cause the same ObjectContext to be used multiple times. So basically, calling parallel via WCF creates multiple ObjectContexts where executing within the WCF service only uses one (which as you know, is not thread-safe). Depending on the nature of your inserts this might be okay. You could also spin up multiple ObjectContexts within the service.
Some of this is wild guessing, because you can actually influence the behavior of the WCF service to not run multiple instances, but judging from the behavior your experience, this should be the reason, why you can perform parallel inserts using the WCF service and not within the WCF service.