HttpContext.Current.Session is null in thread

2

Hello, I have a problem with my code. I'm doing a function that lasts about 3/4 hours in length, and so I decided to do that function on a thread so it does not block the overall system operation. after some research I found some solutions and tested it. But during this function I access the database and when I do this my thread crashes error:

  

HttpContext.Current.Session is null

I then searched for some means of passing the context and the session and I got to these 2 results:

var ctx = HttpContext.Current;
        ThreadPool.QueueUserWorkItem(new WaitCallback(ExecuteLongOperation), ctx);

e:

     HttpContext ctx = HttpContext.Current;
    Thread t = new Thread(new ThreadStart(() =>
    {
        HttpContext.Current = ctx;
        ExecuteLongOperation();
    }));
    t.Start();

Until this point the HttpContext.Current.Session has the session with value, all right.

and in my method:

  private void ExecuteLongOperation(object state)
    {
        try
        {
            HttpContext.Current = (HttpContext)state;  .....}

And when I give a quickwatch in the HttpContext.Current.Session, it remains null.

What am I doing wrong? I tried to pass the session but it is read-only.

Any suggestions? Thanks

    
asked by anonymous 06.10.2016 / 20:49

1 answer

0

The session is part of the request context. When the request is terminated, the session ceases to exist. In other words, you are trying to access an object that is session dependent on a method that is not.

If you need session values, pass these values to your method. Passing a session reference also will not work for the reason stated above.

If you are using .net > = 4.5.2, you can use the HostingEnvironment.QueueBackgroundWorkItem for this.

Usage example here .

    
07.10.2016 / 15:15