Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session and Thread in ASP.NET

Tags:

c#

asp.net

I have a ASP.NET website where a thread is responible for doing some code retrived from a database queue.

Is it possible to get access to the Session or pass that as a parameter ?

My current code looks a follows:

MediaJob nextJob = GetNextJobFromDB();

CreateMedia media = new CreateMedia();

Thread t = new Thread(new parameterizedThreadStart(media.DOSTUFF);

t.Start(nextJob);

The HttpContext.Current.Session is null when running in a thread, so cant do that

like image 330
Millerbean Avatar asked Nov 25 '25 14:11

Millerbean


2 Answers

If your job gets done outside the asp.net thread, then its probably not safe to assume that session would be available. Only deterministic way would be to pass this data explicitly to the thread. You can do this by assigning data in a named data slot

like image 93
np-hard Avatar answered Nov 27 '25 02:11

np-hard


edited:

 HttpContext ctx = HttpContext.Current;
 Thread t = new Thread(new ThreadStart(() =>
                {
                    HttpContext.Current = ctx;
                    worker.DoWork();
                }));
 t.Start();
 // [... do other job ...]
 t.Join();
like image 39
Royi Namir Avatar answered Nov 27 '25 04:11

Royi Namir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!