简体   繁体   English

如何获取从另一个实例声明的静态属性。 C#

[英]How to get a static property declared from another instance. c#

My C# application is executed and set a variable static "_user". 我的C#应用​​程序已执行,并设置了一个静态变量“ _user”。 Afterwords another application is executed under the same process and it must read that variable. 后记另一个应用程序在相同的过程下执行,并且它必须读取该变量。 I cannot obtain the expected results. 我无法获得预期的结果。

  • Application 1: Setting a _user variable: 应用程序1:设置_user变量:

     public class Program { public static void Main(string[] args) { LoginDialog login = new LoginDialog(); login.RunDialog(); } } 
  • Class called by Application which set the variable _User Application调用的类,它设置变量_User

     public class LoginDialog { private static string _user; public void RunDialog() { _user = "Peter"; } public static string User { get { return _user; } } } 
  • Application 2: Get static variable declared: 应用程序2:获取声明的静态变量:

     public class Program { public static void Main(string[] args) { string s = LoginDialog.User; } } 

That's impossible, because each process has its own address space and thus its own instance of LoginDialog.User . 这是不可能的,因为每个进程都有自己的地址空间,因此也有自己的LoginDialog.User实例。 You need to use some kind of inter process communication like Shared Memory or Named Pipes. 您需要使用某种类型的进程间通信,例如共享内存或命名管道。

BTW: Starting one application from the other will not lead to one process that executes both applications. 顺便说一句:从另一个启动一个应用程序不会导致一个进程执行两个应用程序。 Each application has its own process. 每个应用程序都有其自己的过程。

Static data only lives as long as the application domain (AppDomain). 静态数据的寿命与应用程序域 (AppDomain)一样长。 When the AppDomain is unloaded, its memory is released, and any data stored in that memory is lost. 卸载AppDomain时,将释放其内存,并且该内存中存储的所有数据都会丢失。

If, in your Main method, you first call LoginDialog.RunDialog() , you should get the expected result. 如果在Main方法中首先调用LoginDialog.RunDialog() ,则应获得预期的结果。

If you really need the login to run in a separate AppDomain, you'll need to persist some data to a well-known location on the disk, or use some other method of inter-process communication . 如果确实需要登录名在单独的AppDomain中运行,则需要将一些数据持久保存到磁盘上的某个知名位置,或者使用其他进程间通信方法

I suspect that whatever's hosting your applications is creating a new AppDomain for each application. 我怀疑托管您的应用程序的任何对象都在为每个应用程序创建一个新的AppDomain That segregates them from each other pretty much as if they were in different processes. 这将它们彼此隔离,就好像它们处于不同的过程中一样。

I suggest you save the results to disk, rather than trying to use static variables. 我建议您将结果保存到磁盘,而不要尝试使用静态变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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