Our team is developing a machine that will perform a physical process on a tray that holds vials of medical samples. The physical process will take approximately 1.5 hours. The tray and related vials are entities, loaded from a database using the Entity Framework. As the process runs, the device will update values on the entities. The changes may happen minutes or seconds apart. At the end of certain steps, between 10 and 45 minutes apart, we want to save those entities back to the database, and keep going.
Is it acceptable to have an Entity Framework context open for 1.5 hours? Can I make changes and save the entities multiple times during that time period using that context? If not, what is the best way to handle this?
Some ideas so far:
A combination of 2 and 3 will be ideal.
First off, do not keep a context open for hours at a time. You can do this through configuration but it is just going to waste resources considering that you are doing an operation for 90 minutes and it should take roughly 3 milliseconds to open a connection.
So just create a context as you need it. Next, keep in mind that although you open a context to gather data or maintain state, you do not actually need to save the data if it is not ready to be stored. You can just store it locally.
This is where step 3 comes in, with local memory. Basically you should keep it in local memory with an event handler attached. As the local copy changes, have the database update if the change has occurred within some acceptable time window.
Is it acceptable to have an Entity Framework context open for 1.5 hours?
UPDATE: Per the resources you link, if you allow EF to manage the opening and closing of the connection, it will open the connection as late as possible and close it as early as possible, so that the relatively costly database connection can be returned to the connection pool. The connection will only be held open for the duration that the context exists if you manually manage the database connection.
At the end of certain steps, between 10 and 45 minutes apart, we want to save those entities back to the database, and keep going.
Note that if the client crashes for any reason, the changes kept in memory will be lost. Consider the impact of this when deciding whether you really want to wait that long before persisting your data.
If it is quite certain that this is and will remain an architecture with one or just a few clients writing to a dedicated database, I would opt to keep the code as simple as possible... trading resource inefficiency that does not matter in this very specific case for a lesser chance of programmer error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With