Inversión de Contenedores de Control y Threading / Parallel.ForEach

If I have a service (service-layer object not web service) called WidgetProcessor and that service only has one method named Process() Within that method I use another service (service-layer object). Let's call this service WidgetValidator it has a method Validate() that gets called from within a Parallel.ForEach.

1) I'm assuming if I do nothing that the Validate method, if it performs multiple calculations that it will not be thread safe... correct?
2) What is the proper way to inject the WidgetValidator object. If I inject WidgetValidator at via the constructor and assign it to a class level private variable - seems like that would be less thread safe... well, compared with new'ing up a WidgetValidator inside the Parallel.ForEach. But something about this all leaves me thinking "Code Smell"! Should I just put apply a lock to the code inside the Validate method.

Note: I'm using Ninject as my IoC Container.

preguntado el 03 de mayo de 12 a las 19:05

1 Respuestas

It depends on if the Validator is mutating shared state. If it isn't then you can reuse the same instance. If it is mutating shared variables you can't invoke it concurrently.

contestado el 03 de mayo de 12 a las 19:05

It might change method-local variables. Does each thread get its own local vars. Excuse, been a while since I have done threads. +1 - amigojoe

Local vars are never shared (the CLR does not even provide a safe-code way to do that if you wanted). This is safe. - usr

Cool. Just working through some DDD project with Ninject... and haven't had a project in a long time that had to deal with threading. Thanks - usr - answered - amigojoe

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.