c# – DLL内的单例类可以跨进程共享吗?

前端之家收集整理的这篇文章主要介绍了c# – DLL内的单例类可以跨进程共享吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在创建一个自定义的.net硬件框架,由其他程序员用来控制一些硬件.他们将添加对我们的DLL的引用,以获得我们的硬件框架.我需要一个可以从多个应用程序(进程)访问的共享类.

单例模式似乎是我需要的,但它只适用于您的进程中的多个线程.我可能完全错了,但这里是我目前拥有的C#代码的例子.我不禁感到设计不正确.我希望我可以分享更多具体的信息,但我不能.

>我必须强调,我无法控制客户的申请.解决方案必须包含在框架(DLL)本身内.

框架:(共享DLL)

  1. public class Resources
  2. {
  3. static readonly Resources m_instance = new Resources();
  4.  
  5. public string Data;
  6.  
  7. private Resources()
  8. {
  9. Data = DateTime.Now.ToString();
  10. }
  11.  
  12. public static Resources Instance
  13. {
  14. get
  15. {
  16. return m_instance;
  17. }
  18. }
  19. }

测试应用:(最终客户应用程序)

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Console.WriteLine("Press enter to capture the resource!");
  6. Console.ReadLine();
  7.  
  8. var resources = Resources.Instance;
  9. Console.WriteLine("\r\n{0}: {1}\r\n",Thread.CurrentThread.ManagedThreadId,resources.Data);
  10.  
  11. BackgroundWorker worker = new BackgroundWorker();
  12. worker.DoWork += WorkerDoWork;
  13. worker.RunWorkerAsync();
  14.  
  15. while (worker.IsBusy)
  16. {
  17. Thread.Sleep(100);
  18. }
  19.  
  20. Console.WriteLine("Press enter to close the process!");
  21. Console.ReadLine();
  22. }
  23.  
  24. static void WorkerDoWork(object sender,DoWorkEventArgs e)
  25. {
  26. var resources = Resources.Instance;
  27. Console.WriteLine("\r\n{0}: {1}\r\n",resources.Data);
  28. }
  29. }

第一个启动的应用程序提供以下输出

Press enter to capture the resource!

1: 6/24/2009 8:27:34 AM

3: 6/24/2009 8:27:34 AM

Press enter to close the process!

第二个应用程序提供以下输出

Press enter to capture the resource!

9: 6/24/2009 8:27:35 AM

10: 6/24/2009 8:27:35 AM

Press enter to close the process!

结论:

我想看到两个应用程序返回与该类的第一个实例化时间相同的字符串.

正如你可以看到,单程工作的过程中的多线程,但不是跨进程.也许这不能做,因为我似乎找不到任何解决方案.

解决方法

您不能使用单例来跨应用程序同步.每个运行在自己的应用程序空间中,并且作为安全性不能访问内存/对象/等等.从另一个没有通信方法(如遥控)要同步两个他们将不得不远程进入第三个程序.

猜你在找的C#相关文章