title: Async Update Session Data
body: <p>I find several answers bashing use of session state in async fashion, eg.</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/5118236/sessions-in-asynchronous-design">Sessions in Asynchronous design</a></li>
  <li><a href="https://stackoverflow.com/questions/5096789/asynchronous-threads-and-session">Asynchronous threads and session</a></li>
  </ul>
  
  <p>Are there some conditions under which updating session from async thread will not or can not work?</p>
  
  <p>My use case is as follows:</p>
  
  <p>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.</p>
  
  <p>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</p>
  
  <p>I find the following code updates a session key asynchronously. </p>
  
  <pre><code>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 =&gt;
          {
              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 &amp;&amp; Session[MyKey] != null)
              result=  Session[MyKey].ToString();
  
          return Content(result);
         //Refresh until see updated timestamp
      }
  
  
  }
  </code></pre>
  
  <p>Are there any additional considerations or protections - besides a null check - that I should take when writing to session data from the async task?</p>