1

According to the docs, instance members are not guaranteed to be thread safe. That seems odd to me because on every request a new instance of the controller is created, so why would there be any problem?

What I'd like to do is the following:

public MyController : Controller { private string _myAwesomeUserName; protected override void OnAuthorization(AuthorizationContext filterContext) { _myAwesomeUserName = "BobIsTheMan"; } public ActionResult ViewSnowboardCollection() { return View(_myAwesomeUserName); } } 

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

https://msdn.microsoft.com/en-us/library/system.web.mvc.controller%28v=vs.118%29.aspx

1
  • 4
    Each request creates a new instance of the controller. They're not threadsafe in the sense that controller classes are classes just like any other. If you were to write threaded code that invoked methods on the controller, then you would have problems. If you're just using them for web requests handled by IIS, then you're fine, and you can treat them as threadsafe. Commented Jul 22, 2015 at 0:05

1 Answer 1

1

every request a new instance of the controller is created

If anything, this amplifies the potential of accessing shared state.

The Thread-Safety statement in MSDN documents is essentially boiler-plate information. Unless specified otherwise, objects are usually not guaranteed to be thread-safe. Of course, that doesn't mean they are completely unsafe, just that they won't promise to be thread-safe.

According to Wikipedia's article on thread safety:

A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time.

Since it's possible for Controllers to access shared data at the same time, thread-safety cannot be guaranteed.

Sign up to request clarification or add additional context in comments.

1 Comment

So in my example the instance variable is a private, value-type rather than a reference type, so that data would be thread-safe. What's not thread-safe would be if I have a private variable that is a reference type pointing to an object that is also pointed to by a different instance of the controller class?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.