[英]Entity Framework + SQL Server Compact + WPF/WinForms = Sluggish UI?
Entity Framework doesn't allow sharing the same entity between multiple database contexts. 实体框架不允许在多个数据库上下文之间共享同一实体。 Therefore, I have to use only one database context in a GUI application (be it WPF or WinForms), because entities need to interact with each other.
因此,我必须在GUI应用程序中使用一个数据库上下文 (无论是WPF还是WinForms),因为实体需要相互交互。
SQL Server Compact doesn't allow sharing the same database connection between multiple threads . SQL Server Compact不允许在多个线程之间共享相同的数据库连接 。 If I try creating a connection on one thread and running SQL query on another, my application is likely to crash.
如果我尝试在一个线程上创建连接并在另一个线程上运行SQL查询,我的应用程序可能会崩溃。
Therefore, I have to create EF database context on one thread and run all queries on that thread . 因此,我必须在一个线程上创建EF数据库上下文并在该线程上运行所有查询 。 I've used GUI thread for that, because almost all queries are very fast.
我已经使用了GUI线程,因为几乎所有查询都非常快。 However, now I have a slow query and want to show an animated progress bar while it's being executed.
但是,现在我的查询速度很慢,并希望在执行时显示动画进度条。
But I can't do that, because if I run a query on a different thread, my app crashes with AV. 但是我不能这样做,因为如果我在不同的线程上运行查询,我的应用程序会崩溃。 Furthermore, EF seems to complain if I run multiple queries simultaneously , even without SQL CE involved.
此外,即使没有涉及SQL CE,如果我同时运行多个查询 ,EF似乎也会抱怨。 Moving all queries to a different thread, covering all code with crazy amounts of async/await, callbacks, locks and other threading stuff sounds scary too, as I want to keep the code simple if it's possible.
将所有查询移动到另一个线程,用疯狂的async / await,回调,锁和其他线程内容覆盖所有代码听起来也很可怕,因为我想在可能的情况下保持代码简单。
Question: What is the correct way to work with EF database contexts and SQL Server Compact in a multi-threaded GUI application? 问题:在多线程GUI应用程序中使用EF数据库上下文和SQL Server Compact的正确方法是什么? Is there any way to offload individual queries to a different thread without making the whole application asynchronous, ie is there a simple way to do it?
有没有办法将单个查询卸载到不同的线程而不会使整个应用程序异步,即有一种简单的方法吗?
SQL Server CE supports multithreading. SQL Server CE支持多线程。 But its objects like SqlCeConnection or SqlCeTransaction are not thread-safe.
但它的对象如SqlCeConnection或SqlCeTransaction不是线程安全的。 Each thread should use a separate connection.
每个线程都应该使用单独的连接。 An Entity Framework DataContext instance is designed to last for one unit of work (bussiness transaction).
实体框架DataContext实例旨在持续一个工作单元(业务事务)。 The recommendation is a context per a form.
建议是每个表单的上下文。
You can either redesign your application and store/transfer data using DTOs . 您可以使用DTO重新设计应用程序并存储/传输数据。 Or you can use Attach/Detach features of Entity Framework ( here or here ).
或者您可以使用实体框架的附加/分离功能( 此处或此处 )。 Or combine both.
或两者结合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.