【发布时间】:2014-07-25 13:48:29
【问题描述】:
我创建了一个单例类如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace EnergyManager
{
public class Singleton
{
private static Singleton istanza;
public static Services Service;
private Singleton(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length == 0)
{
Services.BehaviourType ProgramBehavior = new Services.BehaviourType();
ProgramBehavior = Services.BehaviourType.NationalProviderConsole;
Service = Services.Instance(ProgramBehavior);
Application.Run(Service.SelectedFormTabs);
}
else
{
Service.ModifyTerminal(Convert.ToInt32(args[0]), Convert.ToInt32(args[1]), Convert.ToInt32(args[2]));
}
}
public static Singleton Instance(string[] args)
{
if (istanza == null)
{
istanza = new Singleton(args);
}
return istanza;
}
}
}
我想做的是,当 args 不为 null 时,它会接收类 Services 的当前状态,我会继续处理该状态。
这个类单例由 Program.cs 调用
static void Main(string[] args=null)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Singleton Sing = Singleton.Instance(args);
}
那是入口点。假设 exe 名为 Test.exe。
问题是,工作情况是这样的: 我首先在没有命令行参数的情况下运行 Test.exe,然后在类单例中创建实例服务。然后我再次使用一些命令行参数运行 Test.exe。因此,当在 Program.cs 中调用 Singleton.Instance(args) 时,在 Singleton 类中它进入 if 的 else 条件,但未实例化服务。这是因为我运行的两个exe看不到对方的状态。如何修改代码,使第二次运行 Test.exe 时,得到第一次运行的 Test.exe 的状态?
【问题讨论】:
-
在执行之间保持数据/状态的唯一方法是将其保存到文件中。
-
进程间通信是一个相当大的话题。您是否只想让代码的多个活动实例交互,或者在没有实例运行时保持状态?
标签: c# singleton exe interaction