Note that there are some explanatory texts on larger screens.

plurals
  1. POImplementing a Session Timeout for a Console App in C#
    text
    copied!<p>I am implementing a Timeout for my console application in C#. I have a class called MySession which has to be bound by a Session timeout. This means that in the constructor of the class, I configure a timeout for the objects created. If any method in the class is not called within that specified timeout, then on subsequent access of any methods, a Timeout exception has to be thrown.</p> <p>This is the dummy implementation of that class.</p> <pre><code>public class MySession { private TimeSpan timeout; private DateTime lastAccessedTime; public MySession(TimeSpan timeout) { this.timeout = timeout; lastAccessedTime = DateTime.Now; } public void StoreName(string name) { TimeSpan diff = DateTime.Now - lastAccessedTime; if(diff.Ticks - timeout.Ticks &gt; 0) { throw new TimeoutException("session timed out"); } //store logic lastAccessedTime = DateTime.Now; } public void StoreAddress(string address) { TimeSpan diff = DateTime.Now - lastAccessedTime; if(diff.Ticks - timeout.Ticks &gt; 0) { throw new TimeoutException("session timed out"); } //store logic lastAccessedTime = DateTime.Now; } public void Commit() { TimeSpan diff = DateTime.Now - lastAccessedTime; if(diff.Ticks - timeout.Ticks &gt; 0) { throw new TimeoutException("session timed out"); } //commit logic lastAccessedTime = DateTime.Now; }} </code></pre> <p>I have a two questions. </p> <ol> <li>Is there a better way to do this that avoids the checking that comes at the beginning of every method? I can obviously refactor a IsAlive property out of that code, but nonetheless I still need to check for IsAlive at the beginning of every method. Is there any Session class in .NET that I could inherit my class from?</li> <li>Hypothetically, let me say that one of my methods in the session class returns another object. Any calls on this object also needs to be considered as updating the lastaccessed time from a timeout perspective. This could soon get pretty complicated with multiple nested objects. But this is only a hypothetical question and maybe YAGNI; but I would like to know if there is any way this can be accomplished.</li> </ol> <hr> <p>EDIT: (since these points were not mentioned in the original question)</p> <ol> <li>The Session class does indeed have a rollback method. I just did not add it to keep the code small!</li> <li>The Stores actually go to a backend database within the scope of a database transaction. So all Store calls in this class, would actually write the data to the database, but commit on the DB needs to happen only after commit on the session is called.</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload