Skip to main content
 首页 » 编程设计

c#之DBContext多线程

2024年02月20日12xxx_UU

我有一个我在 VS2010 中使用 MVC3 (Razor) 构建的网站

我使用 DBContexts 访问数据库,我的连接字符串是:

<add name="SystemDBContext" 
connectionString="Data Source=|DataDirectory|System.sdf" 
providerName="System.Data.SqlServerCe.4.0" /> 

我想要一个游戏循环,所以我在 Application_Start 中启动了一个新线程,它循环并使用 DBContext 访问数据库。

似乎正在发生的事情是循环使用 DBContext 并锁定 db 文件,然后每当您尝试从网站本身的 DBContext 进行更改时,该文件正在使用中。

不是在我声明 DBContext 时发生,而是在我尝试使用 DBContext 执行某种搜索或更新时发生。

这是我的 Global.asax

    protected void Application_Start() 
    { 
        ... 
        Manager m = new Manager(); 
        Thread t = new Thread(m.Start); 
        t.Start(); 
    } 

我的一个 Controller 的一部分:

public class myController : Controller 
{ 
    private SystemDBContext db = new SystemDBContext(); 
 
 
    public ViewResult Index() 
    { 
        var engines = db.Engines.Include(e => e.state); 
        return View(engines.ToList()); 
    } 
    ... 

我的循环看起来像这样:

public class Manager 
{ 
    public void Start() 
    { 
        while (true) 
        { 
            SystemDBContext db = new SystemDBContext(); 
            var query = from ... 
        } 
        ... 

执行此操作的最佳做​​法是什么?我一直在考虑单例、锁或同步时钟,调整连接字符串以允许多次附加到数据库文件,或者让我的循环请求执行更新的网页。

有什么想法吗?

请您参考如下方法:

What seems to be happening is that the loop uses the DBContext and locks the db file, and then whenever you try to make changes from the DBContext on the website itself, the file is in use.

回到阅读文档?它说 WinCE 不是多线程服务器的部分。请改用 SQL Server - Express is free . CE 适用于可扩展性有限的项目,单线程访问。

What is the best practice for doing this?

使用合适的数据库服务器。 CE 存在严重问题,特别是如果您一直启动/停止数据库引擎,这会导致大量磁盘访问效率低下。

SQL Server 正是为此而做的,正如我所说 - Express 很便宜。