winforms - Windows 服务无法打开 Windows 窗体
问题描述
我正在尝试创建一个Windows Service
usingTopShelf
并且在此服务中我想启动一个Windows Form
.After 我创建了服务并调试了它调用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 隔离(防止Shatter 攻击的一项重要安全措施)已成为法律的世界中,您应该非常仔细地考虑任何依赖服务交互的设计。
最佳实践是重组您的解决方案,使其具有:
- 在后台运行的服务,独立于用户
- 与服务交互并可由任何用户运行的传统 GUI 应用程序
推荐阅读
- python - 在python中将多个嵌套的JSON转换为CSV
- javascript - 是否可以在项目中将 CSS 字符串文本更改为 CSS 代码?
- postgresql - 如何使用 PostgreSQL 的“pg_restore”和零停机恢复数据?
- html - 使用 DataTables 如何显示每行输入的金额的累计?
- node.js - NodeJS 以编程方式读取为 Github Pages 中的自定义域创建的 CNAME 文件
- javascript - “你可能需要一个额外的加载器来处理这些加载器的结果。”
- angularjs - mat-slider 显示负值,初始值为 0,没有轨道填充
- python - 下标运算符的不同位置导致熊猫 groupby 的结果相同
- sql - 订单管理 SQL 模式
- python - ImportError: DLL load failed: 找不到指定的模块?