简体   繁体   中英

How do you use variables across C# classes while resetting them every call?

I am creating a web API in ASP.Net with IIS. However, I have been storing class members statically so that they can be accessed across different classes. This is obviously bad practice and I am noticing that every time a request is being made for the API, the same values are being returned due to the members not being cleared. How would I clear the members every request while also being able to access them across classes?

You should almost never use static variables in a web application. Even if you want to share variables across requests, access to statics is not thread-safe in many cases, and that can result in corrupt memory, incorrect system behavior, and even total system failure (if you're unlucky).

If you have variables that need to be shared, use an application variable instead. If you need to have a common cache, use one of the established caching techniques .

As for your specific question

How would I clear the members every request while also being able to access them across classes?

I think there is a misunderstanding here. There is no absolutely no reason to re-use a variable if it is being reset every time. I am guessing you think there is a performance cost to allocating new variables with each request; this is false. It is actually less efficient to use shared variables as multiple threads will experience false sharing and have to wait for each other as each request completes. If you use a new set each time, each thread has its own sandbox to work in and can complete the request much more quickly.

Instead, store your variables locally or as member variables in an object that is discarded at the end of the request. If you need some common location across all modules within a request, you can use HttpContext.Item or one of its alternatives .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM