Passing an Entity to a different thread

Posts   
 
    
slade52
User
Posts: 46
Joined: 15-Aug-2007
# Posted on: 26-Mar-2008 06:38:51   

Hi, I'm wondering if it is safe to do code like this:

(SelfServicing)

in my main thread (dfc is an EntityCollection):


foreach(DataFileEntity df in dfc)
{
  AutoResetEvent waitEvent = new AutoResetEvent(false);
  waitHandles.Add(waitEvent);

  FileProcessorThreadState state = new FileProcessorThreadState();
  state.WaitEvent = waitEvent;
  state.DataFile = df;

  ThreadPool.QueueUserWorkItem(
    new WaitCallback(FileProcessor.Go),
     state);
}

the threadstate class:


    class FileProcessorThreadState
    {
        public AutoResetEvent WaitEvent;
        public DataFileEntity DataFile;
    }

and the thread worker:


class FileProcessor
{
  public static void Go(object state)
  {
     FileProcessorThreadState threadState = (FileProcessorThreadState)state;

            <snip>

    threadState.DataFile.Save();

    threadState.WaitEvent.Set();
  }
}

Code simplified to show the concept.... I guess the simple version is: Is it safe to update and save a SelfServicing entity on a different thread to the one it was created on ?

Luckily (perhaps) the entity is not involved in a Transaction. I doubt I'd consider this approach if that was the case.

Thanks in advance for any comments and advice.

Regards Mike

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 26-Mar-2008 10:18:26   

An entity is not threadsafe, you still can pass it to another thread to process it, but don't re-use it in more than one thread at the same time, and if you want to use it in the original thread after it was processed in the worker thread, you should either refetch it from the database or pass it back from the worker thread.

Please check the following thread: http://www.llblgen.com/TinyForum/Messages.aspx?ThreadID=10635

slade52
User
Posts: 46
Joined: 15-Aug-2007
# Posted on: 26-Mar-2008 22:31:18   

Walaa, thanks again for your help. That clears things up for me. Regards Mike