如何在不同线程中使用实体框架? [英] How to work with Entity Framework in different threads?

查看:49
本文介绍了如何在不同线程中使用实体框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体框架 dbContext 和方法,可以对数据库进行一些操作.如何从多个线程正确调用它以避免死锁,连接错误等?我尝试了不同的方式,但有很多例外.

 公共无效Foo(酒吧){使用(var db = new ApplicationDbContext()){db.Documents.Add(bar);...db.SaveChanges();}}静态void Main(string [] args){...var t1 = new Thread(()=> Foo(bar1));thread.Start();var t2 = new Thread(()=> Foo(bar2));thread.Start();...} 

我以前从未使用过线程.感谢您的帮助.

解决方案

DbContext不是线程安全的,最好的方法是为每个工作单元(在您的情况下为每个线程)创建DbContext的单独实例.请参见建议.

I have an Entity Framework dbContext and method which makes some manipulations with database. How to properly call it from multiple threads to avoid deadlocks, connection errors and so on? I tried it different ways, and I had a lot of exceptions.

public void Foo(Bar bar)
{
    using (var db = new ApplicationDbContext())
    {
        db.Documents.Add(bar);
        ...
        db.SaveChanges();
    }
}

static void Main(string[] args)
{
    ...
    var t1 = new Thread(()=>Foo(bar1));
    thread.Start();

    var t2 = new Thread(()=>Foo(bar2));
    thread.Start();
    ...
}

I never used threads before. Thanks for your help.

解决方案

DbContext isn't thread safe and the best approach is to create separate instance of DbContext per unit of work (in your case per thread). See the recommendations.

这篇关于如何在不同线程中使用实体框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆