gpt4 book ai didi

c# - 防止控制台在调试时关闭

转载 作者:行者123 更新时间:2023-11-30 22:14:07 25 4
gpt4 key购买 nike

我的问题是控制台应该保持打开状态。当 Console.ReadLine() 等待输入时,计时器无法将任何内容写入控制台。如何在不使用 Console.ReadLine()、Console.ReadKey() 或 system("pause") 的情况下防止控制台关闭?

这是我的代码:

namespace Closer {
public static class Program {
public static void Main () {
// Define timer
var t = new Windows.Forms.Timer() {
Enabled = true,
Interval = 30000
};

// Give timer the tick function
t.Tick += (object tSender, EventArgs tE) => {
// If it is half past eleven
if (DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() == "2330") {
// Close all osu!.exe's --- works
foreach (Process p in Process.GetProcessesByName("osu!")) {
p.Kill();
}

// Write a msg
Console.WriteLine("Done!");
}
};

// Prevent the console from closing --- Here's the problem
Console.ReadLine();
}
}
}

最佳答案

你把两个问题混为一谈了。是的,早期版本的 .NET 4.5 犯了一个错误,即让 Console.ReadLine() 获取锁以阻止线程写入控制台。已修复,只需打开 Windows 更新即可获取服务版本。

真正的问题是您的 Timer 类选择。 System.Windows.Forms.Timer 需要一个消息循环来触发 Tick 事件。您只能通过调用 Application.Run() 来获得消息循环。顺便说一下,Console.ReadLine() 的一个非常合适的替代品,使用 Application.ExitThread() 让您的应用程序终止。

您应该在控制台模式应用程序中使用 System.Threading.Timer 或 System.Timers.Timer。它们的回调在线程池线程上触发,因此不需要调度程序循环。

关于c# - 防止控制台在调试时关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18663152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com