36

我目前正在使用带有控制台应用程序的 TopShelf 来创建 Windows 服务。当我将代码作为控制台应用程序运行时,我使用了一些 Console.WriteLine() 来输出结果。一旦代码完成了它应该做的事情,我将控制台应用程序安装为 Windows 服务。

即使 Windows 服务无法写入控制台,离开 Console.WriteLine() 代码是否有任何缺点?如果我将 Console.WriteLine() 留在其中,是否存在代码不稳定的风险?

4

5 回答 5

38

输出将被简单地丢弃

在 Windows 服务中没有控制台,因此 Console.Write* 输出被丢弃。有多种选择:

  1. System.Diagnostics.Trace 类具有与 Console 类类似的接口,因此您可以很容易地将代码迁移到此。
  2. 然后可以将其配置为输出到文件。您可以使用 System.Diagnostics.EventLog 类写入事件日志,然后您可以使用事件查看器对其进行监控。
  3. 您可以使用非常灵活的第三方开源 log4net 库。
于 2012-01-09T18:04:07.473 回答
9

不,控制台类将安全地写入 STDOUT,但您将看不到输出。

于 2012-01-09T18:04:52.810 回答
3

如果您使用 System.Diagnostics.Trace 功能,您可以使用侦听器和开关重定向输出。如果您使用 TRACE 符号编译,则将包含代码。如果不添加 TRACE,则不会将其编译到项目中。

如果您将服务作为控制台运行以进行调试,则默认情况下 Trace 将输出到控制台。我已经开始使用 Trace 而不是 Debug 或 Console writes,因为我可以从配置文件中将跟踪信息输出到文件、屏幕、数据库等的任意组合。

于 2012-01-09T20:39:04.817 回答
2

在 Windows Server 2008R2 之前,输出始终被丢弃。将 console.writeline() 留在安装在该操作系统上的服务中,在启动/运行服务时会收到错误 1067,具体取决于 writeline() 的位置。

于 2014-03-21T01:07:47.100 回答
1

还想根据命令行显示帮助。
我的解决方案是打开一个新控制台。

internal static class NativeMethods
{
    [DllImport("user32.dll")]
    internal static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    internal static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

    [DllImport("kernel32.dll")]
    internal static extern bool AllocConsole();

    [DllImport("kernel32.dll")]
    internal static extern IntPtr GetConsoleWindow();
}

public static void ShowWindow(IntPtr hWnd, ShowWindowCommand cmd = ShowWindowCommand.Restore)
{
    NativeMethods.SetForegroundWindow(hWnd);
    NativeMethods.ShowWindowAsync(hWnd, (int)cmd);
}

public static void ShowConsoleWindow()
{
    var handle = NativeMethods.GetConsoleWindow();

    if (handle == IntPtr.Zero)
        NativeMethods.AllocConsole();
    else
        ShowWindow(handle, ShowWindowCommand.Show);
}

ShowWindowCommand 只是从这里构建的枚举
https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow

Edit:
That solution worked for years but currently fails. Unclear if it is related to a Windows- or VisualStudio update. Definitly does not work on W10 20H2 and VS2019 16.9.x

于 2020-09-01T10:13:26.533 回答