Httpcontext.Current.Session is null in thread

Asked

Viewed 879 times

2

Hi, I have a problem with my code. I’m doing a function that lasts about 3/4 hours long, and then I decided to do this function in a thread so that it doesn’t block the overall functioning of the system. After some research I found some solutions and tested. However during this function I access the bank and when I do this my thread breaks error:

Httpcontext.Current.Session is null

then I looked for aind ways to pass context and Session and arrived at those 2 result:

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

and:

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

up to this point Httpcontext.Current.Session has Session with value, all right.

and in my way:

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

and when I give a quickwatch on Httpcontext.Current.Session, it remains null.

What am I doing wrong? I already tried to pass Ssion but she is read-only.

Any suggestions? Thank you

1 answer

0


Session is part of the request context. When the request ends, Session ceases to exist. In other words, you are trying to access an object that is dependent on the request (Session) in a method that is not.

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

If you are using . net >= 4.5.2, you can use HostingEnvironment.QueueBackgroundWorkItem for that reason.

Example of use here.

  • 1

    your comment helped me a lot, I needed to send a reference of my application, to be able to create data ORM depends on the session of my application, so I passed to the thread a application and inside created a session to ensure atomicity of the application. Anyway Thanks for your help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.