.NET Core 1.1控制台应用程序始终作为Ubuntu 16.04上的systemd服务退出/崩溃

时间:2017-05-06 08:20:50

标签: c# linux .net-core daemon systemd

我正在尝试创建一个简单的echo服务,它与systemd init系统一起使用。一切都很好,它甚至在快速部署后开始,但是当我试图通过systemctl status <service>命令找出它的状态时,它会快速退出(或崩溃)。

逻辑很简单,我在这里提供下一个来源:

Program.cs的

using System;
using System.Threading.Tasks;

namespace hw
{
    class Program
    {
        private const int delay = 1000;
        private static Random random = new Random();

        static async Task Handle()
        {
            Console.WriteLine($"tick tack... {random.Next()}");
            await Task.Delay(delay);
            await Handle();
        }

        static void Main(string[] args)
        {
            Task.Factory.StartNew(async() => await Handle());
            Console.ReadLine();
        }
    }
}

hw.service(systemd config file)

[Unit]
Description=HW Echo Service

[Service]
WorkingDirectory=/var/netcore/hw
ExecStart=/usr/bin/dotnet /var/netcore/hw/hw.dll
Restart=always
RestartSec=10
SyslogIdentifier=dotnet-echo-hw

[Install]
WantedBy=multi-user.target

帮助脚本,init.sh (如果您想在本地系统上试用,也可以使用chmod +x init.sh):

dotnet build
dotnet publish

echo "\nPreparing binaries for the service directory:\n"
rm -rf /var/netcore/hw
mkdir /var/netcore /var/netcore/hw
cp -R bin/Debug/netcoreapp1.1/publish/* /var/netcore/hw
ls -la /var/netcore/hw

echo "\nInitializing the systemd service:"
systemctl stop hw.service
rm /etc/systemd/system/hw.service
cp hw.service /etc/systemd/system/hw.service
systemctl daemon-reload
systemctl enable hw.service
systemctl start hw.service
systemctl status hw.service

日志:

我还在等什么?

我希望我的服务运行,因为其他我的服务(ASP.NET Core)正在运行(具有活动/绿色状态)作为Execute R服务。至于ASP.NET核心项目,没有问题,就像简单的控制台一样 - 它们是......

如何解决我的问题?

由于

1 个答案:

答案 0 :(得分:1)

由于 Evk 建议使用ManualResetEvent,我已完成下一步:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace hw
{
    class Program
    {
        private const int delay = 1000;
        private static Random random = new Random();
        private static ManualResetEvent resetEvent = new ManualResetEvent(false);

        static async Task Handle()
        {
            Console.WriteLine($"tick tack... {random.Next()}");
            await Task.Delay(delay);
            await Handle();
        }

        static void Main(string[] args)
        {
            Task.Factory.StartNew(async() => await Handle());
            Console.CancelKeyPress += (sender, eventArgs) => 
            {
                // Cancel the cancellation to allow the program to shutdown cleanly.
                eventArgs.Cancel = true;
                resetEvent.Set();
            };
            resetEvent.WaitOne();
        }
    }
}

现在一切正常服务不会停止/崩溃。