views:

135

answers:

2

Hey, I have a list of objects,

for each object i want to run a totally separate thread (thread safty),like....i will pick one a object from my list in while loop and run a thread and then for next object run the next threads...all thread should be synchronized such that resources (values/connection (close/open) )shared by them should not change.....

+2  A: 

Starting a thread per object is not necessarily wise; you should probably have a small number of worker threads picking items off the list (or better, a Queue<T>), synchronizing access to that list/queue. An example of a thread-safe queue can be found in this thread.

Once you have a work item, there is no magic bullet for making the rest of the code you write (to process it) thread-safe. A sensible approach that keeps things simple is immutability - either true immutability (the items can't change), or simply don't change the object. You can of course implement locking around the work item, but this only helps if all your code uses the same locking strategy, which is hard to enforce.

Marc Gravell
+1  A: 

i will pick one a object from my list in while loop and run a thread and then for next object run the next threads

If I really wanted a thread per object, which I probably wouldn't, I would create a class like this:

class ObjectProcessingThread
{
Thread processingThread = new Thread();
public TargetObject { get; set;}

public Start()
{
    //start the processing thread with threadEntryPoint as the work the thread will do
} 

private threadEntryPoint
{
   //do stuff with targetObject
}
}

Then in the while loop new up an ObjectProcessingThread for each object, setting it's TargetObject property, then calling Start.

all thread should be synchronized such that resources (values/connection (close/open) )shared by them should not change.....

If you don't want values to change, don't change them.

AaronLS