问题描述
我正在尝试创建 Web API 服务,但是当我尝试作为服务运行时,我收到 NullReferenceException
.如果我删除 ServiceBase
部分,它运行良好.如果我将 Thread 替换为什么都不做,那么它会照常工作.
I'm trying to create a Web API service but when I'm trying to run as service I get NullReferenceException
. It's working well if I remove the ServiceBase
part. If I replace the Thread to do nothing, then it's working as usual.
什么可能导致 NullReferenceException
?
namespace WebApi
{
public class Program
{
public static void Main(string[] args)
{
//To Debug
//BuildWebHost(args).Run();
//To Run as Service
using (var service = new TestService())
{
ServiceBase.Run(service);
}
}
public static IWebHostBuilder BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://localhost:5000");
}
}
class TestService : ServiceBase
{
public TestService()
{
ServiceName = "TestService";
}
protected override void OnStart(string[] args)
{
string filename = CheckFileExists();
File.AppendAllText(filename, $"{DateTime.Now} started.{Environment.NewLine}");
Thread t = new Thread(new ThreadStart(Program.BuildWebHost(args).Build().Run));
t.Start();
}
protected override void OnStop()
{
string filename = CheckFileExists();
File.AppendAllText(filename, $"{DateTime.Now} stopped.{Environment.NewLine}");
}
private static string CheckFileExists()
{
string filename = @"c:\tmp\MyService.txt";
if (!File.Exists(filename))
{
File.Create(filename);
}
return filename;
}
}
推荐答案
通过代码很难找到 NullReferene.但是您可以使用以下方法使其可调试:
It is hard to find the NullReferene by code. But you can make it debuggable with the following approach:
var s1 = new TestService();
if (!Environment.UserInteractive)
ServiceBase.Run(new ServiceBase[] { s1 }); // when running as service
else
{
s1.Start(args); // when running as console
Console.ReadLine();
s1.Stop();
}
这将作为 Windows 服务或控制台应用程序启动.
this will start as windows service or console application.
把这段代码放到Program.Main
方法中并在debug下运行.
Put this code to the Program.Main
method and run under debug.
PS 有 Topshelf library 也可以为您处理这些东西(将应用程序作为服务或控制台运行).
PS there is Topshelf library also that can deal this stuff for you (run application as service or console).
PPS 似乎您需要添加 public void TestService.Start
方法才能使此 UserInteractive
方法有效:
PPS seems that you will need to add public void TestService.Start
method to make this UserInteractive
approach works:
public class TestService : ServiceBase
{
// existing code
public void Start(string[] args)
{
OnStart(args);
}
public void Stop()
{
OnStop();
}
}
这篇关于Windows 服务 NullReferenceException C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!