Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
Posted

1 solution

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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900