我应该如何在线程化 WinForms 应用程序中使用 EF4?
我有一个 winforms 应用程序,它只读取日志文件。现在,因为我有几个日志文件(例如 20-30 个),所以我尝试使 winform 应用程序线程化,以便它可以一次读取多个日志文件。
但我不确定应该如何处理日志文件数据的保存。
1. 每个线程一个上下文
例如,如果每个被解析的线程日志文件都有自己的 EF4 上下文并进行保存(例如,每 1000 条记录或 EOF 时)
,或者
2. WinForm 线程的一个上下文
如果 winform 应用程序让每个后台线程报告一个上下文,并返回一组日志文件条目,并且主 winform 线程每 x 条记录或 x 秒或其他内容保存它...
我只是不确定应该将上下文放在哪里.. . 更重要的是......为什么我应该把它放在任何地方。
有人有什么建议吗?
I've got a winforms app which just reads log files. Now, because I have a couple of log files (say, 20-30), I've tried to make the winform app threaded, so it can read multiple log files at once.
But i'm not sure how I should be handling the saving of the log file data.
1. One Context Per Thread
For example, should each threaded log file that is parsed, have it's own EF4 context and does the save (eg. every 1000 records or when EOF)
or
2. One Context for the WinForm Thread
Should the winform app have the single context an each background thread report back with a collection of log file entries and the main winform thread saves it every x records or x seconds or something...
I'm just not sure where I should be putting the context ... and more importantly ... why I should put it where ever.
Does anyone have any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上,EF 上下文只能在创建它的线程中使用。如果您跨线程使用上下文,某些事情可能会按预期工作,但不能保证,因为根据文档,ObjectContext 不是线程安全的。例如,延迟加载似乎不适用于跨线程< /a>.
为了回答您的问题,我认为您的第一个选择(每个线程一个上下文)是最好的(前提是您限制并发线程的数量)。让所有工作线程调用表单来插入数据会冻结 UI 并阻止工作线程有效工作。
Basically, a EF context can only be used from the thread that created it. Some things might work as expected if you use the context accross threads, but there is no guarantee, as ObjectContext is not thread-safe according to the documentation. For instance, lazy loading doesn't seem to work accross threads.
To answer your question, I think your first option (one context per thread) is the best (provided you limit the number of concurrent threads). Having all worker threads calling the form to insert the data would freeze the UI and prevent worker threads from working efficiently.
我认为这两种方法都是有效的。当每个线程处理单独的日志数据时,您可以一直访问数据库并为每个线程使用一个 EF 上下文,并让您的 RDBMS 处理并发问题。
如果您关心性能,则必须衡量哪种方法性能更好。这可能主要取决于您的数据库系统/表布局。
I think both approaches are valid. When every thread processed separate logdata, you can go all the way to the database and use one EF context per thread and let your rdbms handle the concurrency issues.
If you are concerned about performance, you have to measure which approach performs better. That might depend mainly on your database system / table layout.