I find several answers bashing use of session state in async fashion, eg.
Are there some conditions under which updating session from async thread will not or can not work?
My use case is as follows:
In app, user profile data is stored in session. Aim to asynchronously refresh the profile data when an admin changes a user's name, groups, or other profile info, etc.
Async thrust: poll a database table that stores the user id's whose data has changed. if data matches current user id, refresh profile data, remove id from table
I find the following code updates a session key asynchronously.
public class MyAsyncUpdateController : Controller
{
public static string MyKey = "myKey";
public ActionResult Index()
{
Session[MyKey] = "Init Data: Updated at " + DateTime.Now.TimeOfDay;
Task.Factory.StartNew(session =>
{
Thread.Sleep(10000);
var _session = (HttpSessionState)session;
if (_session != null)
_session[MyKey] = "Async Data: Updated at " + DateTime.Now.TimeOfDay ;
}, System.Web.HttpContext.Current.Session);
return RedirectToAction("OtherAction");
}
public ActionResult OtherAction()
{
string result = "";
if (Session != null && Session[MyKey] != null)
result= Session[MyKey].ToString();
return Content(result);
//Refresh until see updated timestamp
}
}
Are there any additional considerations or protections - besides a null check - that I should take when writing to session data from the async task?