1

Following this question about the thread-safety of DbContext (it isn't), I need to know if it's safe to handle mapped POCOs in multiple threads.

Suppose I have two objects mapped to the database using CodeFirst:

class Poco1
{
    public int Id { get; set; }
    public string SomeProp {get; set;}
    public virtual List<Poco2> children { get; set; }
}

class Poco2
{
    public int id { get; set;}
    public Poco1 parent { get; set; }
}

In the main thread I'm loading Poco1:

var parentPoco = _context.Poco1s.Where(...).Single();

I then pass it to a task, where I create another object and change the parent a bit

var childPoco = new Poco2 { parent=parentPoco }; 
parentPoco.SomeProp = "Tasked!";

Then back in the main thread I add childPoco to the context:

_context.Poco2s.Add(childPoco);
_context.SaveChanges();

I am not doing anything with the context in the secondary thread, but I am manipulating objects that are mapped to it.

Can I do that?

Community
  • 1
  • 1
zmbq
  • 38,013
  • 14
  • 101
  • 171
  • As long as you keep a worker class that holds the dataContext and dish out POCOs from that then everything should be safe as the dataContext holds the object graph – Paul Sullivan Oct 10 '12 at 20:55
  • What do you mean 'dish out POCOs from that'? I just create them with new. – zmbq Oct 10 '12 at 20:56
  • I don't believe the scenario you describe would be thread-safe, And unless you use some form of synchronization, you're likely to get race-conditions. POCO classes are just basic classes after all. Why are you resorting to threading? – Stewart Ritchie Oct 11 '12 at 09:42
  • I have an asynchronous MVC action, and I want to manipulate POCOs in the task. I have no problem with *my* synchronization, I'm worried about cross-POCO and internal structures used by DbContext - ones I am not aware of and can't synchronize. – zmbq Oct 11 '12 at 12:04

1 Answers1

1

If they're "pure" POCOs (no change tracking or lazy loading), with no references to any other object used in the "original" thread, then you're fine. But most people use "impure" POCO proxies, which are not safe to use from a concurrent thread.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273