如何在Windows服务上有效地使用Entity框架 [英] How do I used Entity framework effectively on a windows service

查看:50
本文介绍了如何在Windows服务上有效地使用Entity框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





在当前项目中,我们要求使用无限运行的Windows服务。此服务基本上监视队列。在任何消息到达它基本上更新数据库表中的信息(多个表受影响)



此外,这个Windows服务将产生多个线程来并行执行此工作。为了增加复杂性,有多个Windows服务实例在不同的服务器上运行。



现在来问题陈述......

使用

实施实体框架的最佳方法1.使用寿命更长的应用程序

2.使用多线程

3.使用服务访问并行表



我想知道。

1.我们什么时候应该启动DBContext

2。如何锁定特定表以避免多个线程/进程未处理相同的记录

3.如何避免DbContext的失效状态(缓存数据)



谢谢

Madhukar

Hi,

In out current project we have a requirement to use Windows service which is infinitely running. This service basically monitors a queue. On any message arrival it basically update the information in database tables (multiple table are affected)

Also this windows service will spawn multiple threads to perform this work in parallel. To add in more complexity there are multiple instances of the windows services running on different servers.

Now coming to the problem statement...
What is best way to implement Entity Framework with
1. Application having longer lifetime
2. With Multi threading
3. With services accessing table in parallel

I want to know.
1. When should we initiate the DBContext
2. How do I lock specific table to avoid same record not processed by multiple threads/processes
3. How do I avoid stale state of DbContext (Cached data)

Thanks
Madhukar

推荐答案

A1:我不知道更长寿命是什么意思

A2:实体框架是线程安全的

A3:使用交易范围*



B1:仅在您使用时

B2:使用交易范围*

B3:使用交易范围小心*





实体框架是线程安全的。避免使用相同的DBConext实例来避免死锁。 DBContext应该在单个事务的生命周期中实例化恕我直言。



您可以使用几个隔离级别进行事务处理。有些将确保在更新数据时,表读取总是以许多表锁的代价获得最新数据,有些将牺牲可访问性的准确性。



< a href =http://www.codeproject.com/Articles/690136/All-About-TransactionScope>您应该阅读事务隔离级别并选择一个最适合您的目的。



我更喜欢快照。我的单个事务可以独立工作,并允许其他查询同时从表中读取。在交易完成之前,数据将保持不变,但这适合我的应用程序。
A1: I don't know what "longer lifetime" means
A2: Entity framework is thread safe
A3: Use transaction scope*

B1: Only when you use it
B2: Use transaction scope*
B3: Use transaction scope carefully*


Entity framework is thread safe. avoid using the same instance of the DBConext to avoid deadlocks. The DBContext should be instantiated for the lifetime of a single transaction IMHO.

There are several isolation levels you can use for a transaction. Some will ensure that a table read always has the latest data at the cost of many table locks when the data is updated, and some will sacrifice accuracy for accessibility.

You should read up on transaction isolation levels and pick one that is best for your purposes.

I prefer snapshot. I single transaction can work in isolation and allow other queries to read from the table at the same time. The data will be unchanged until the transaction is complete, but this suits my app.


这篇关于如何在Windows服务上有效地使用Entity框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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