Csharp/C#教程:Topshelf – 基于自定义参数启动线程分享


Topshelf – 基于自定义参数启动线程

我做了一个使用自定义参数的topshelf webservice:

string department = null; // *********************Below is a TopShelf code*****************************// HostFactory.Run(hostConfigurator => { hostConfigurator.AddCommandLineDefinition("department", f => { department = f; }); //Define new parameter hostConfigurator.ApplyCommandLine(); //apply it Helpers.LogFile("xxx", "Got department:"+department); hostConfigurator.Service(serviceConfigurator => { serviceConfigurator.ConstructUsing(() => new MyService(department)); //what service we are using serviceConfigurator.WhenStarted(myService => myService.Start()); //what to run on start serviceConfigurator.WhenStopped(myService => myService.Stop()); // and on stop } ); hostConfigurator.RunAsLocalService(); //****************Change those names for other services*******************************************// 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只是写入文本文件。 您可以从上面的代码中看到参数department传递给MyService(string d) 。 当我使用调试时,一切正常,即“-department:workshop”作为调试参数。 但是,当我尝试使用callforward.exe install -department:logistics将程序作为服务callforward.exe install -department:logistics时,我在检查日志时创建了服务callforwardservice_logistics bu,该参数尚未传递给MyService。

我究竟做错了什么?

默认情况下,Topshelf似乎不支持向服务启动配置添加自定义参数,安装后HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesMyService下的ImagePath值不包含其他参数-department:... 您可以inheritance默认的WindowsHostEnvironment并重载Install方法,但我认为将以下代码添加到主机配置代码会更容易(可能更不好):

上述就是C#学习教程:Topshelf – 基于自定义参数启动线程分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

  // *********************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)); } }); ... } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1028280.html

(0)
上一篇 2022年1月10日
下一篇 2022年1月10日

精彩推荐