How does HttpContext.Current work in a multi-threaded environment?

后端 未结 2 559
刺人心
刺人心 2020-12-03 08:13

So I\'m left wondering how exactly asp.net is able to scope a static property, when (to my knowledge) asp.net is multi-threaded.

  • One theory goes that the ASP.N
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 09:03

    It isn't an AppDomain per-request. If you want to use thread-specific state, try:

    [ThreadStatic]
    private static int foo;
    public static int Foo {get {return foo;} set {foo = value;}}
    

    Each thread now gets its own value of Foo (or rather: 'foo').

    This is not to be used lightly - it does have costs, but is a valid way of sharing state on a per-thread basis. I've used this once, maybe twice - and I've written a lot of C#. Don't over-use it...

    In particular, watch out for initialization issues (i.e. forgetting to do it), and remember to clean up after yourself etc. And be very careful if you use any async code, as any callbacks/workers/etc will have different state.

提交回复
热议问题