0

I know if I have a static class with static properties, then that state will be shared with all threads that are running.

1) But lets say I have a non static class with a static property will that static property (which changes per login, i.e. session_token) be shared across all threads?

If it is shared, then things like session variables cannot be stored in a static property.

2) How would one do this?

marwaha.ks
  • 540
  • 1
  • 7
  • 19
  • My first intuition: the static properties should not differ depending on static/not static class (Note: i'm not sure, it just a (n educated) guess). However, storing session data in some static value doesn't seem that good of an idea. You could store it in a static property, but I would suggest then using a static class that has some form of dictionary behaviour to retrieve only specific requested items, and not just entire user data without proper indication – H.J. Meijer May 29 '18 at 08:47
  • A static anything is shared, no matter if it's in a static class or not. Take a look at ThreadLocal if you need something per thread, but I dont think you're going to be able to use that with session related things. ASP is a different beast when it comes to using shared state – pinkfloydx33 May 29 '18 at 08:48
  • @H.J.Meijer even if i used a dictionary the threads will be overwriting each key. – marwaha.ks May 30 '18 at 07:47
  • @pinkfloydx33 Yeah atm I've got like 20 static strings with the attribute `[ThreadStatic]` but I don't think this is an elegant way to do it. – marwaha.ks May 30 '18 at 07:48
  • ThreadStatic attribute is different from the ThreadLocal class. The attribute only applies to fields I believe; it will also only initialize the values once (for the first thread) and the rest is up to you. ThreadLocal is my preference. – pinkfloydx33 May 30 '18 at 08:46
  • @pinkfloydx33 do you have any examples on how you would use it? – marwaha.ks Jun 01 '18 at 08:34

1 Answers1

0

1)

Static variables are shared across all instances of the class, whether or not the class is static.

A better explanation can be found at this question:

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

2)

Session variables can be stored in statics. Just because they are global do not mean they are immutable, simply change the static property when the session ID changes.

  • Lets say i have `static string session_token`, when I have one thread running then this is fine. When I have >1 thread(T) writing to `session_token` then T2 overwrites T2 and they both will use T2 and my tests are screwed. – marwaha.ks May 30 '18 at 07:10
  • In this case I wouldn't use a static, because the point of a static is that it is global for all. You could try having an initial session ID static, and then a new non static for any instances after the first one. – Nathan Osamodas Craven May 30 '18 at 09:23