What is the scope of a Static Class?

烂漫一生 提交于 2019-11-27 13:48:45

问题


I have an assembly that may be used by more than one process at a time. If I am using a static class, would the multiple processes all use the same "instance" of that class?

Since the processes are separate, would these be running under difference Application Domains, hence have the static "instances" separate?

The pudding in the details here is that the assembly is being used by a custom BizTalk adapter that my be set to process the messages in parallel batches. That is what I am calling "multiple processes" above.


回答1:


Multiple threads would share an instance. For this reason a static class can be convenient for passing state between threads, but you need to be very careful not to introduce race conditions (Monitor or lock your properties).

However, multiple processes should be in separate AppDomains and therefore each have their own instance.




回答2:


Static classes exist once per application domain. In your case, it would depend on whether the adapter is using multiple threads in the same application domain (thus sharing a single instance of the static class) or using multiple processes (thus having separate instances of the static class).




回答3:


"I have an assembly that may be used by more than one process at a time. If I am using a static class, would the multiple processes all use the same "instance" of that class?"

No, they all have separate instances.

"Since the processes are separate, would these be running under difference Application Domains, hence have the static "instances" separate?"

Yes.




回答4:


The scope of a static class is limited to the application domain. Each app domain will have its own copy of any static variables you might have. If your "processes" are threads within the same app domain, then they will share the static values. But if they are actual separate Windows processes, then they will have different app domains and hence separate copies.




回答5:


You may want to look at the Singleton pattern. The gist seems to be you want to control the number of service instances.

I'm guessing that you want a separate dll/project servicing all the client requests. You could use static class/singleton/multiton to implement the desired functionality. It really depends on what you are trying to accomplish.



来源:https://stackoverflow.com/questions/284491/what-is-the-scope-of-a-static-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!