Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all,
I'm currently building some stuff into a web application and the application uses session state to 'remember' a user. It's an existing application, so I can't change that.
Now in the user object I want to update a property and all is well.
However, on one occassion I want to set it from a worker thread.

So, in my Controller I have something like this:
C#
// Somewhere at login...
this.Session["user"] = myUser;

// In another method call...
var user = (User)this.Session["user"];
user.SomeProperty = myValue; // e.g. 1.

// In yet another method call...
var user = (User)this.Session["user"];
var myValue = user.SomeProperty; // myValue would be 1.
// myValue now has the value we stored earlier.

That works really great!

Now in another Controller I have the following:
C#
// In some method call...
var user = (User)this.Session["user"];
Task.Factory.StartNew(() =>
{
    // Some long-running process...
    user.SomeProperty = myValue; // e.g. 2.
});
// return some value and handle it in JavaScript on client.
// The task will finish the long-running process on the server on a different thread and the user can switch pages, etc.

// In another method call AFTER the long-running process finishes...
var user = (User)this.Session["user"];
var myValue = user.SomeProperty; // myValue is 1.
// myValue doesn't have the value stored in the worker thread :(

So now I read that storing a value in the session is thread-dependent. I tried running a follow-up task and force it to run on the main thread, but the main thread is, of course, gone.
So is there any way to update this variable into my session on the worker thread?

Thanks.
Posted
Comments
DamithSL 12-Jan-15 11:35am    
after you update user properties you need to set
Session["user"] = user ;
then only you can get updated value back
Richard Deeming 12-Jan-15 12:01pm    
Only if User is a struct, or you're using an out-of-process session state server. If User is a class, and you're using the default in-process session state, the updated property values will automatically be saved.
Sander Rossel 12-Jan-15 16:09pm    
Thanks for your reply.
I tried that, but even that didn't work.
It seems the value is set per thread, so if I set it on a different thread the value on my main thread won't be updated...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900