Sharing Variables between Threads in .Net
Have you ever needed to use a common value in .Net in multiple threads?
For example, there is a back-end server for handling clients’ requests. We have giant data stored in cache to share between requests, but it takes significant time and RAM capacity to deserialize data from cache and store in a new variable.
In this case, one way is to use static variables to share them between multiple different threads (requests). We once deserialize and store data in one thread from cache into a static variable in RAM, and then use the shared variable from different requests. Notice that we might update the cache data, so we need to read data from cache again, but there is a gap time between writing the variable and reading it. Therefore, we must lock the static variable while reading or writing. In such cases, we use an object(or the same static variable) in order to lock the access from/to that scope static variable used in to avoid conflicting issues.
Here's the code in my repository:
I hope this article helps you. If so, please star my repo and like and share this article.
Do you know other ways to do so? Please comment.
Thanks guys