gpt4 book ai didi

c# - Topshelf - 根据自定义参数启动线程

转载 作者:太空宇宙 更新时间:2023-11-03 10:31:48 28 4
gpt4 key购买 nike

我制作了一个使用自定义参数的 topshelf 网络服务:

string department = null;

// *********************Below is a TopShelf
HostFactory.Run(hostConfigurator =>
{
//Define new parameter
hostConfigurator.ApplyCommandLine();
//apply it
hostConfigurator.AddCommandLineDefinition("department", f => { department = f; });

Helpers.LogFile("xxx", "Got department:"+department);

hostConfigurator.Service<MyService>(serviceConfigurator =>
{
//what service we are using
serviceConfigurator.ConstructUsing(() => new MyService(department));
//what to run on start
serviceConfigurator.WhenStarted(myService => myService.Start());
// and on stop
serviceConfigurator.WhenStopped(myService => myService.Stop());
}

hostConfigurator.RunAsLocalService();

//****************Change those names for other
string d = "CallForwardService_" + department;

hostConfigurator.SetDisplayName(d);
hostConfigurator.SetDescription("CallForward using Topshelf");
hostConfigurator.SetServiceName(d);
});



public class MyService
{
string depTask;
public MyService(string d)
{
//***********************Three tasks for three different destinations
depTask = d;
_taskL = new Task(Logistics);
_taskP = new Task(Planners);
_taskW = new Task(Workshop);
Helpers.LogFile(depTask, "started working on threads for "+d);

public void Start()
{
if (depTask == "logistics")
{
_taskL.Start();
Helpers.LogFile(depTask, "proper thread selected");
}
}
}
}

Helpers.logfile 只是写入文本文件。 Aa 你可以从上面的代码中看到参数 department 被传递给了 MyService(string d)。当我使用“-department:workshop”作为调试参数进行调试时,一切正常。但是当我尝试将程序安装为服务时callforward.exe install -department:logistics 我确实创建了服务 callforwardservice_logistics 但是当我检查日志时参数没有传递给 MyService。

我做错了什么?

最佳答案

默认情况下,Topshelf 似乎不支持将自定义参数添加到服务启动配置中,并且安装后 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService 下的 ImagePath 值不包含附加参数 -department:...。您可以继承默认的 WindowsHostEnvironment 并重载 Install 方法,但我认为将以下代码添加到您的主机配置代码会更容易(可能不太好):

// *********************Below is a TopShelf code*****************************//
HostFactory.Run(hostConfigurator =>
{
...
hc.AfterInstall(ihc =>
{
using (RegistryKey system = Registry.LocalMachine.OpenSubKey("System"))
using (RegistryKey currentControlSet = system.OpenSubKey("CurrentControlSet"))
using (RegistryKey services = currentControlSet.OpenSubKey("Services"))
using (RegistryKey service = services.OpenSubKey(ihc.ServiceName, true))
{
const String v = "ImagePath";
var imagePath = (String)service.GetValue(v);
service.SetValue(v, imagePath + String.Format(" -department \"{0}\"", department));
}
});
...
}

关于c# - Topshelf - 根据自定义参数启动线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29837596/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com