Millerbean
Millerbean

Reputation: 295

Session and Thread in 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

Upvotes: 3

Views: 6363

Answers (3)

Royi Namir
Royi Namir

Reputation: 148524

edited:

 HttpContext ctx = HttpContext.Current;
 Thread t = new Thread(new ThreadStart(() =>
                {
                    HttpContext.Current = ctx;
                    worker.DoWork();
                }));
 t.Start();
 // [... do other job ...]
 t.Join();

Upvotes: 3

Johann
Johann

Reputation: 12398

You can't access the session from within a thread, but you could share your data using: HttpRuntime.Cache

There are a few things to keep in mind though: unlike session, cache do expire. Also the cache is shared between all web users.

Upvotes: 0

np-hard
np-hard

Reputation: 5815

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

Upvotes: 3

Related Questions