c# - 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#i
from 该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 中尝试在异常设置中检查所有要中断的异常。
解决方案
如果您从单个线程写入控制台,请尝试改用它:
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();
}
推荐阅读
- r - R Notebook中折叠的TOC
- swift - 实例成员 'query' 不能用于类型 'GeoFire';你的意思是使用这种类型的值吗?
- json - NET Core Ok() 在 Angular 中返回格式化为字符串的 json
- typescript - 删除键并将其添加回扩展类型对象时,打字稿不匹配类型
- java - Kotlin 中具有泛型参数的不同(继承)类对象的 ArrayList
- ethereum - 为什么无法解码这个以太坊 tx 输入数据?
- python - IndexError: list index out of range in model.fit() [添加验证数据时出错]
- react-native - 当 numColumns 为 3 时处理 flatlist 中的空格
- c++ - 如何在 C++ 中创建一个比较未知数量字符串的方法?
- python - 简单项目的设计模式[工厂 vs 原型]?