[英]Prevent the console from closing while debugging
我的問題是控制台應該保持打開狀態。 在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 Update即可獲取服務版本。
但是真正的問題是您選擇Timer類。 System.Windows.Forms.Timer需要消息循環才能觸發Tick事件。 您只能通過調用Application.Run()獲得消息循環。 非常適合替代Console.ReadLine(),請使用Application.ExitThread()使應用終止。
您應該在控制台模式應用程序中使用System.Threading.Timer或System.Timers.Timer。 他們的回調在線程池線程上觸發,因此不需要調度程序循環。
您應該使用System.Timers.Timer
,一切正常。
static void Main()
{
// Define timer
System.Timers.Timer t = new System.Timers.Timer()
{
Enabled = true,
Interval = 1000
};
// Give timer the tick function
t.Elapsed += (object tSender, System.Timers.ElapsedEventArgs tE) =>
{
Console.WriteLine("Done!");
};
Console.ReadLine();
}
您可以嘗試以下方法:
Thread.CurrentThread.Join();
我知道這很愚蠢,但這可以滿足您的需求。 而且該過程將永遠不會終止,您必須手動殺死它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.