title: HttpContext.Current.Session is null on timed event
body: <p>I have developed an e-commerce system based on <strong>ASP.NET</strong> and an ERP system, Microsoft Dynamics AX 4.0.</p>
  
  <p>For each HTTP session, I logon to the ERP system using a <em>"Business connector"</em>, a .NET component. The <em>"Business connector"</em>-object is stored in a <strong>session-variable</strong>. So at a normal <strong>Session_end</strong>, I will log out from Dynamics AX and clean up all resources</p>
  
  <p>The ERP system is a 32-bit based system, and to save resources I would like to develop a timer that logs out of the ERP-system after a certain time of inactivity. Lets say 2 minutes. The <strong>Http session timeout</strong> is set for 20 minutes. </p>
  
  <p>I made a class, "TimerHandler" that uses <code>System.Timers.Timer</code>, that starts and restarts the timer every time the user click on something related to the ERP system (items, basket etc). </p>
  
  <p>Example code: </p>
  
  <pre><code>public class ErpHandler
  {
      private ErpTimerHandler TimerHandler
      {
          get
          {
              if (HttpContext.Current != null)
              {
                  if (HttpContext.Current.Session["TimerHandler"] != null)
                  {
                      return (ErpTimerHandler)HttpContext.Current.Session["TimerHandler"];
                  }
              }
              return null;
          }
         set
          {
              if (HttpContext.Current != null)
              {
                  HttpContext.Current.Session["TimerHandler"] = value;
              }
          }
      }
  
      private void StartTimer()
      {
          ErpTimerHandler timer = TimerHandler;
          if timer == null)
          {
              timer = TimerHandler.Instance();
              timer.TimerEvent += OnTimedEvent;   
              TimerHandler = timer;
          }
  
          timer.StartTimer();
  
      }
  
      private void StopTimer()
      {
          ErpTimerHandler timer = TimerHandler;
          if (timer != null)
          {
              timer.StopTimer();
              TimerHandler = null;
          }
      }
  
      private void OnTimedEvent(Object source, EventArgs e)
      {
          StopTimer();
          ErpLogOff();
      }
  
      public void ErpLogOff()
      {
          ErpSystem erp = ErpInstance;            
          if (LoggedOnErp &amp;&amp; erp != null)
          {
              erp.Logoff();
              ErpInstance = null;
          }
          LoggedOnErp = false;
  
      }
  }
  </code></pre>
  
  <p>This code will never log off the Erp on <code>OnTimedEvent</code>, as <code>HttpContext.Current.Session</code> is null. </p>
  
  <p>From what I understand, the timer is running on a different thread, hence the current session is not available when I need it. </p>
  
  <p>So how on earth can I "reach" that thread? Or can i make sure the timer run on the same thread as the session? </p>