首页 > 解决方案 > C# 代码执行停止,没有任何异常

问题描述

我有一个带有 .NET Framework 4.7.2 和Colorful.Console 1.2.6 的 C# 控制台应用程序(我从 1.2.9 降级,因为我有另一个使用 1.2.6 的项目可以完美运行)。
我有这个类用于记录:

static class Log
{
    public enum LogLevel { INFO = 0, WARNING = 1, ERROR = 2, VERBOSE = 3 }
    private static void log(LogLevel logLevel, string msg)
    {
        Color[] colors = { Color.Cyan, Color.Orange, Color.Red, Color.LimeGreen };
        Console.WriteLineFormatted($"[{DateTime.Now.ToString("hh:mm:ss")}][{logLevel.ToString()}] {{0}}", Color.Yellow, new Formatter(msg, colors[(int)logLevel]));
    }

    public static void i(string msg)
    {
        log(LogLevel.INFO, msg);
    }
    public static void w(string msg)
    {
        log(LogLevel.WARNING, msg);
    }
    public static void e(string msg)
    {
        log(LogLevel.ERROR, msg);
    }
    public static void v(string msg)
    {
        log(LogLevel.VERBOSE, msg);
    }
}

当我使用Log#ifrom 该Program#Main方法时,它工作得很好,但是如果我Log#i从另一个 calss 调用它会显示该行并且程序完全停止而没有错误(并且它不会崩溃)

Console.WriteLineFormatted($"[{DateTime.Now.ToString("hh:mm:ss")}][{logLevel.ToString()}] {{0}}", Color.Yellow, new Formatter(msg, colors[(int)logLevel]));

行,应用程序停止响应(但它没有写在标题栏中)。
该程序如下所示:

class Program
{
    private static OverlayForm overlayForm;
    static void Main(string[] args)
    {
        Log.i("A");
        Log.i("B");

        overlayForm = new OverlayForm();
    }
}

internal class OverlayForm : Form
{
    public OverlayForm()
    {
        Log.i("AA");
        Log.i("BB");
    }
}

输出是这样的:

[10:12:36][INFO] A 
[10:12:36][INFO] B 
[10:12:36][INFO] AA

我已经尝试将提到的行包含在 try catch 块中,但没有区别,我还在 VS2019 中尝试在异常设置中检查所有要中断的异常。

标签: c#

解决方案


如果您从单个线程写入控制台,请尝试改用它:

private static void log(LogLevel logLevel, string msg)
    {
        ConsoleColor[] colors = { ConsoleColor.Cyan, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.Green };

        Console.ForegroundColor = colors[(int)logLevel];
        Console.WriteLine("[{0}][{1}] {2}", DateTime.Now.ToString("hh:mm:ss"), logLevel, msg);
        Console.ResetColor();
    }

推荐阅读