title: Asp.Net Core - Using Session variables in task
body: <p>I'm building a simulator with Asp.Net application where simulation is done as a separate task. I'm having problem with accessing data which is processed in this task.</p>
  
  <p>I've tried to access task or threat I created, but don't see a way to track created task. </p>
  
  <p>I've also tried to use Session, but after request is completed I have no access to Session anymore, so background task stops with error.</p>
  
  <p><strong>LatheController:</strong></p>
  
  <pre><code>public class LatheController : Controller
  {
      private readonly ApiDbContext _dbContext;
      private static ILatheService _latheService;
  
      public LatheController(ApiDbContext dbContext)
      {
          _dbContext = dbContext;
      }
  
      [HttpGet]
      public LatheCell GetLatheCell()
      {
          if (_latheService == null)
          {
             _latheService = new LatheService();
  
              _latheService.Start(lc);
          }
  
          return _latheService.GetLatheCell();
      }
  
  
      [HttpGet("{id}")]
      public LatheCell GetLatheCell([FromRoute]int id)
      {
          return AppHttpContext.Current.Session.GetObjectFromJson&lt;LatheCell&gt;("latheCell");
      }
  }
  </code></pre>
  
  <p><strong>LatheService:</strong></p>
  
  <pre><code>public class LatheService : ILatheService
  {
      private LatheSimulator _latheSim;
  
      public void Start(LatheCell lc)
      {
          _latheSim = new LatheSimulator(lc);
  
          Task task = new Task( () =&gt; { _latheSim.Start(); });
          task.Start();
      }
  
      public LatheCell GetLatheCell()
      {
          return _latheSim.GetLatheCell();
      }
  }
  </code></pre>
  
  <p><strong>LatheSimulator:</strong></p>
  
  <pre><code>    public class LatheSimulator
  {
      private LatheCell _latheCell;
      private bool _keepRunning;
  
      public LatheSimulator(LatheCell latheCell)
      {
          _latheCell = latheCell;
      }
  
  
      public void Start()
      {
          _keepRunning = true;
          Simulation();
      }
  
      public void Stop()
      {
          _keepRunning = false;
      }
  
      public LatheCell GetLatheCell()
      {
          return _latheCell;
      }
  
  
      private void Simulation()
      {
          while (_keepRunning)
          {
              _latheCell.RunningCycle++;
              //// The simuation ///
  
              AppHttpContext.Current.Session.SetObjectAsJson("latheCell", _latheCell);
  
              //Sleep operation to simulate speed of the conveyor
              System.Threading.Thread.Sleep(_latheCell.ConveyorIn.Speed);
          }
      }
  }
  </code></pre>
  
  <p><strong>Startup:</strong></p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
      {
          /// ... some other configurations
  
          services.AddMvc();
          services.AddDistributedMemoryCache();
          services.AddSession();
          services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
      }
  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
      { 
         ///....
         app.UseSession();
         AppHttpContext.Services = app.ApplicationServices;
        /// .....
      }
  </code></pre>
  
  <p><strong>AppHttpContext:</strong></p>
  
  <pre><code>public static class AppHttpContext
  {
      static IServiceProvider services = null;
  
      public static IServiceProvider Services
      {
          get { return services; }
          set
          {
              if (services != null)
              {
                  throw new Exception("Can't set once a value has already been set.");
              }
              services = value;
          }
      }
  
      public static HttpContext Current
      {
          get
          {
              IHttpContextAccessor httpContextAccessor = services.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor;
              return httpContextAccessor?.HttpContext;
          }
      }
  }
  </code></pre>
  
  <p>I know I could use database for this, but because I will be calling database every 5 sec in the simulation, I would like to keep simulator in the memory for the performance.</p>
  
  <p>If anyone could put me in the right direction I will be very appreciated. I'm scratching my head for several days now.</p>