开发者

Singleton in .NET shared across all sessions?

I am creating a singleton to hold a linqtoumbraco datacontext which pulls data from a cached xml file.

I understand how to create a singleton class and to use locks to prevent new threads from creating new instances.

I do开发者_如何学Gon't understand multithreading and how .NET sessions work too well and want to know if I create the singleton as described above, will it be shared by all users who hit my web app while the app pool remains alive? In other words, the singleton is not just a singleton for one user session, it is for all sessions?

Thanks


Yes it will be, static members are shared for whole ASP.Net application

Another way to do this, to create and assign datacontext in HttpContext.Current.Application, and you can get it from anywhere you want in any session

But think about it a bit, are all clients only read from xml file? what if one client is reading in the time the other writing? Or are that datacontext supports multithread reading? You should answer all this questions before using that datacontext in static manner


If you store it in a normal static field then yes, it will be shared. You can place the [ThreadStatic] Attribute on the field to tie it to the current thread. Keep in mind that threads can be reused so you'll want to null out the field when you are done with it.


As long as the server instance is alive your singleton will be one shared across the entire app, it's like stuff you initialize on global.asax when server start

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜