我正在尝试创建Web API服务,但是当我尝试作为服务运行时,会显示NullReferenceException
。如果我删除ServiceBase
部分,则效果很好。如果我替换线程不执行任何操作,那么它将照常工作。
什么可能导致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;
}
}
好的,因此您可以在服务启动时在代码中添加一个强制断点:
protected override void OnStart(string[] args)
{
System.Diagnostics.Debugger.Break();
string filename = CheckFileExists();
File.AppendAllText(filename, $"{DateTime.Now} started.{Environment.NewLine}");
Thread t = new Thread(new ThreadStart(Program.BuildWebHost(args).Build().Run));
t.Start();
}
并将调试器附加到该进程,以便您可以查明发生错误的位置。
其他有用信息:http://msdn.microsoft.com/en-us/library/7a50syb3.aspx