I am working on an ASP.NET site where it is required that a single Socket be created and kept connected across all pages for the current session. I have created and stored the socket as a session object and it remains connected after a page redirect, but the connection is closed whenever a postback occurs (such as a button click). Is there any way to keep the socket connection open even after a postback, as the requirement is that a single connection be used for the entire session and reconnecting the socket is not an option.
Share
Session-state is brittle; in fact, what you describe won’t even work if you are using a serializing session-state provider (a socket is not serializable).
So: rather than storing the socket in session, put the socket somewhere else – maybe a synchronized dictionary – and store just a key to it in session. For example:
In usage, if you don’t have a socket (/key) already, create your connection, store it with
Add, and then store the key in session. When fetching, you must handle thenullcase, and you will also want to add your own synchronization, to guard against the same socket being used by two concurrent requests from the same session (perfectly legal).However, as additional notes: