所以我试图在Windows服务中创建一个线程,但我在尝试执行它时收到错误1607。这是我的代码
protected override void OnStart(string[] args)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "Log.txt";
using (sw = File.AppendText(path))
{
sw.WriteLine("the service has started");
server = new Server(sw);
server.start();
start = true;
new Thread(() =>
{
Thread.CurrentThread.IsBackground = false;
/* run your code here */
while (start != true)
{
Thread.Sleep(2000);
}
// tcp ip server
server.started();
}).Start();
}
}
当我在没有线程的情况下运行它时,OnStart程序在服务器结束之前不会结束。基本上当我右键单击服务并启动时,服务器启动,我也可以连接客户端,但状态不会更改为“正在运行”。当服务器代码停止执行时,它将更改为正在运行。这是上面的代码。
protected override void OnStart(string[] args)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "Log.txt";
using (sw = File.AppendText(path))
{
sw.WriteLine("the service has started");
server = new Server(sw);
server.start();
start = true;
// running without thread
server.started();
}
}
上面的代码可以正常工作,但是在右键单击并点击“开始”之后,服务器代码执行完毕后(当所有客户端都离开并且服务器关闭时)状态将更改为“正在运行”。我真的很擅长windows服务,所以请原谅任何愚蠢的错误。
你在OnStart
方法中有这个代码:
using (sw = File.AppendText(path))
{
sw.WriteLine("the service has started");
server = new Server(sw);
server.start();
start = true;
new Thread(() =>
{
Thread.CurrentThread.IsBackground = false;
/* run your code here */
while (start != true)
{
Thread.Sleep(2000);
}
// tcp ip server
server.started();
}).Start();
}
你构造一个Server
对象,传递它对你创建的文件的引用(即sw
)。但是然后你启动线程并退出using
块,它处理文件。
稍后,server
对象尝试写入文件,但它已被处理掉。所以服务器在线程中抛出一个异常,它会冒泡到主程序中,然后惹恼它。
您需要维护对该文件的引用,并在OnStop
上关闭它。
我认为你的问题的答案出现在这里:Windows Service to run constantly
实际上OnStart需要快速返回,你应该启动一个线程来处理你的逻辑。一旦OnStart结束,状态将变为“运行”,因此这与您的观察结果一致。
至于为什么你的进程在另一个线程上运行时结束 - 我认为你的服务器关闭而不管OnStop - 这是停止服务的正确方法。从上面的解释我怀疑一旦所有客户离开就关闭(Environment.Exit或类似)。