Jeova Almeida
Jeova Almeida

Reputation: 95

Share DbContext among threads

We use the pattern 'one dbconnection by request' on our asp.net mvc applications (C# / VS 2k15). Basically we create a DbContext on BeginRequest and Dispose() it on EndRequest.

I used to save this DbContext on HttpContext but we ran into a little more complex scenario where we needed run multiple threads and this solution stopped working since HttpContext is not shared among threads.

First I thought using CallContext but its objects should be Serializable, which isn't the case of DbContext.

The (not optional) solution I thought of was save the DbContexts on a public static Dictionary where the key (long) is the thread id, but I think there's a better solution.

What's the best solution to share DbContext among threads?

Thanks.

Upvotes: 0

Views: 1787

Answers (2)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89386

What's the best solution to share DbContext among threads?

To not do that. A DbContext instance cannot be accessed by multiple threads at the same time.

Just have your background processes create a new DbContext in a using block. The underlying database connections are pooled and will be reused.

If you just want to pass a DbContext instance across the Tasks that flow from a single http request, and can guarantee that it will not be accessed by two concurrent Tasks or Threads, then you can use AsyncLocal.

You can also capture a local variable referring to the DbContext and explicitly pass it to a task you await. EG

await Task.Run(() =>
  {
    var e = db.MyEntity.First();
    //. . . 
   });

Upvotes: 7

Martin Vich
Martin Vich

Reputation: 1082

I'd suggest against doing that.

But if you insist on it and you're using Inversion of Control library than it's quite likely that it will support Per thread lifestyle

Upvotes: 0

Related Questions