ExoticCheeseSticks
ExoticCheeseSticks

Reputation: 160

Threading in ASP.NET MVC 3

I am currently converting a Windows Phone 7 application to its web counterpart. The application uses a big main thread from which the data is gathered, and for the moment I have just copied and pasted it as is (just a standard thread operation), in my ASP.NET MVC controller.

Sync _Sync = new Sync();
_Sync.StartSync();

The tasks work OK, but because the thread makes use of global data set from the cookies, issues arise when accessing the page with 2 different usernames. For example, if I login with "user1" in Firefox and then try to login in Chrome with another user (say "user2"), then it will automatically change the async data gathered for the first user; meaning that I will always see data pulled out from the last user logged in (regardless of the fact that I was just logged in in Firefox with another user, initially), and not each others' separate data.

In other words, the thread doesn't start separately for each individual user. How could I fix this behavior?

Upvotes: 2

Views: 998

Answers (1)

Chris Shouts
Chris Shouts

Reputation: 5427

Static fields and properties are shared across threads and should generally not be used to store data that pertains to a specific user or web request.

One of the following suggestions should fix your threading issues and keep your user data separate.

  • Create an instance of the Sync class for each request and remove any static fields / properties from the class.
  • Add a method to the Sync class that returns an instance of the data for a specific user instead of storing the data in static fields / properties.

Upvotes: 3

Related Questions