我正在尝试使用Windows Service
创建一个TopShelf
,并且在此服务中我想启动一个Windows Form
。创建服务并调试后,调用ShowDialog
表单不显示:
服务
class SimpleServ {
private Task task;
private const string PATH = @"D:/out.txt";
private Logger logger;
private CancellationTokenSource src = new CancellationTokenSource();
public SimpleServ() {
logger = new Logger();
}
public void Start() {
logger.Log("Started");
this.task = Task.Run(async () => {
var fm = new Fm(logger);
while (true) {
fm.ShowDialog();
logger.Log("Just closed the dialog");
await Task.Delay(3000);
}
});
}
public void Stop() {
logger.Log("Stopped service");
}
}
表格
public partial class Fm : Form {
private Logger log;
public Fm(Logger log) {
this.log = log;
this.log.Log("From Form constructor");
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
this.log.Log("Button clicked");
this.Close();
}
}
主要
class Program {
static void Main(string[] args) {
var exitCode = HostFactory.Run(x => {
x.Service<SimpleServ>(s => {
s.ConstructUsing(h => new SimpleServ());
s.WhenStarted(h => h.Start());
s.WhenStopped(h => h.Stop());
});
x.RunAsLocalSystem();
x.SetServiceName("SimpleService");
x.SetDisplayName("Simple Service");
x.SetDescription("Simple serv description");
});
int exitCodeValue = (int)Convert.ChangeType(exitCode, exitCode.GetTypeCode());
Environment.ExitCode = exitCodeValue;
}
}
我已经全心投入这项服务,并且在到达ShowDialog
行之后,什么也没有发生。
更新
我还添加了Logger
来记录所有重要事件,到目前为止,似乎表单已打开,但我看不到它:
记录器
public class Logger {
private string path;
public Logger(string logPath=Constants.PATH) {
this.path = logPath;
}
private object @lock = new object();
public void Log(string message) {
string formattedMessage = "Date:" + DateTime.Now.ToString() + "\tMessage:" + message;
File.AppendAllLines(this.path, new string[] { formattedMessage });
}
}
文件的输出为:
Date:6/12/2019 11:19:13 AM Message:Started
Date:6/12/2019 11:19:13 AM Message:From Form constructor
答案 0 :(得分:1)
在当今世界中,会话0隔离(一种防止Shatter attacks的重要安全措施)是本国法律,对于任何依赖于服务交互的设计,您都应该仔细考虑。
最佳做法是将您的解决方案重组为: