当控制台运行异步任务时,阻止控制台通过ctrl-C终止或多按回车键? [英] Prevent console from terminate by ctrl-C or multi press enter key when console is running async task?
问题描述
大家好,
如何在async任务当前正在运行时或在Await Task.Delay(毫秒)上阻止控制台退出?
目前在我的主要:
Sub Main(ByVal args()As 字符串)
如果args.Length<> 0 然后
Dim i As Integer = 0
虽然我< args.Length
If(args(i))= config然后
HideConsole()
System.Windows.Forms.Application.EnableVisualStyles()
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(False)
System.Windows.Forms.Application.Run(New formsettings)
End if
i = i + 1
End while
Else
ShowConsole()
MaximizeConsole()
Trace.Listeners.Clear()
Dim twtl As New TextWriterTraceListener(AppDomain.CurrentDomain.BaseDirectory& out.txt)
twtl.Name = TextLogger
twtl.TraceOutputOptions = TraceOptions.ThreadId或TraceOptions.DateTime
Dim ctl As New ConsoleTraceListener (False)
ctl.TraceOutputOptions = TraceOptions.DateTime
Trace.Listeners.Add(twtl)
Trace.Listeners.Add(ctl)
Trace.AutoFlush = True
Trace.WriteLine( 程序始于& DateTime.Now.ToString( dd-MM-yyyy HH:mm:ss:fff))
ConsoleStartup()
Console.ReadKey()
结束如果
结束子
其中 ConsoleStartup 是任务按间隔运行的地方。让我们说每隔一小时: -
私人 Sub ConsoleStartup()
尝试
执行
tmr_repeat = TimeSpan.Parse(My.MySettings。 Default .Interval).TotalMilliseconds
For i = 1 7
Console.WriteLine(DateTime.Now.ToString( dd-MM-yyyy HH:mm:ss:fff)& >检查行:{0},i)
dt_local = ShowTotalCount(objlocalconn,i)
Await CompareValue(i)
Next
Dim date1 作为 日期 = 日期。现在
Dim toadd As Integer = TimeSpan.Parse(My.MySettings。 默认 .Interval).TotalSeconds
Dim date3 正如 日期 = date1.AddSeconds(toadd)
Console.WriteLine(DateTime.Now.ToString( dd-MM-yyyy HH:mm:ss:fff)& >重新启动计时器。下一批处理{0},date3.ToString(dateFormat))
等待 Task.Delay(tmr_repeat)
循环
Catch ex 作为例外
结束 尝试
结束 Sub
目前每当我按下Ctrl-C或意外按下Enter键2次时,即使控制台开启,它也会突然终止控制台做一些异步循环任务。我尝试了一些代码,但没有工作,甚至我坚持放置代码并与我的ConsoleStartup Sub合并
我尝试过:
Sub Main(ByVal args()As String)
Dim t As Task = MainAsync(args)
t.Wait()
End Sub
私有函数MainAsync(ByVal args()As String)作为任务
ShowConsole()
MaximizeConsole()
Trace.Listeners.Clear()
Dim twtl As New TextWriterTraceListener(AppDomain.CurrentDomain.BaseDirectory&out.txt )
twtl.Name =TextLogger
twtl.TraceOutputOptions = TraceOptions.ThreadId或TraceOptions.DateTime
Dim ctl As New ConsoleTraceListener(False )
ctl.TraceOutputOptions = TraceOptions.DateTime
Trace.Listeners.Add(twtl)
Trace.Listeners.Add(ctl)
Trace.AutoFlush = True
Trace.WriteLine(程序始于& DateTime.Now.ToString(dd-MM-yy) yy HH:mm:ss:fff))
ConsoleStartup()
Console.ReadKey()
结束函数
我不知道为什么你用C#标记了你的问题,因为你的代码显然不是......无论如何
你看过 SetConsoleCtrlHandler功能(Windows) [ ^ ]?
我在c#中有一个控制台进程,它使用Control-C跳闸一个事件并做更多的工作或在另一个案例中提高向BackgroundWorker发出一个信号,它应该停止它在做什么......在这两种情况下,这就是它进入灰色区域的地方,然后我继续工作,甚至允许再次使用Control-C(而不是评论我看到,建议处理程序必须快速完成其工作,否则专业人士克会变得不稳定..我猜处理程序确实快速完成了它的工作 - 引发了一个事件,但是,Control-C / Control-Break等被困了)我之后可以做任何事情
我很确定VB.Net代码显示了如何使用SetConsoleCtrlHandler - 这可能是 AddressOf.com:Console事件处理 [ ^ ]
对不起,这只回答了你的一部分问题,我不得不考虑键盘部分......在紧要关头我会考虑设置一个标志说'我正在工作',然后当标志'未设置'时,即工作已完成,刷新键盘缓冲区[/ edit]
我正在使用此代码并且它阻止任何键从控制台退出,甚至按下Ctrl-C键。
Pri vate bExit 作为 布尔
私有输入作为 字符串
Sub Main( ByVal args() As 字符串)
bExit = 错误
Console.TreatControlCAsInput = True
MainFunctionStartHere ' 我的主要任务函数将在这里调用
执行
input = Console.ReadLine()' 虽然功能是正在运行,这将
' 开始捕获密钥
如果 input = P 然后
bExit = True
Trace.WriteLine( 退出!)
Task.Delay( 3000 )
结束 如果
循环 (不(bExit))
结束 Sub
我不知道是否有其他方法可以解决我的代码问题
Hi guys,
How to prevent console from exiting while the async task is currently running or on Await Task.Delay(milliseconds)?
Currently on my Main:
Sub Main(ByVal args() As String)
If args.Length <> 0 Then
Dim i As Integer = 0
While i < args.Length
If (args(i)) = "config" Then
HideConsole()
System.Windows.Forms.Application.EnableVisualStyles()
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(False)
System.Windows.Forms.Application.Run(New formsettings)
End If
i = i + 1
End While
Else
ShowConsole()
MaximizeConsole()
Trace.Listeners.Clear()
Dim twtl As New TextWriterTraceListener(AppDomain.CurrentDomain.BaseDirectory & "out.txt")
twtl.Name = "TextLogger"
twtl.TraceOutputOptions = TraceOptions.ThreadId Or TraceOptions.DateTime
Dim ctl As New ConsoleTraceListener(False)
ctl.TraceOutputOptions = TraceOptions.DateTime
Trace.Listeners.Add(twtl)
Trace.Listeners.Add(ctl)
Trace.AutoFlush = True
Trace.WriteLine("Program started at " & DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss:fff"))
ConsoleStartup()
Console.ReadKey()
End If
End Sub
Where ConsoleStartup is where the task will running by interval. Lets say every one hours:-
Private Sub ConsoleStartup()
Try
Do
tmr_repeat = TimeSpan.Parse(My.MySettings.Default.Interval).TotalMilliseconds
For i = 1 To 7
Console.WriteLine(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss:fff") & " > Checking for Line: {0}", i)
dt_local = ShowTotalCount(objlocalconn, i)
Await CompareValue(i)
Next
Dim date1 As Date = Date.Now
Dim toadd As Integer = TimeSpan.Parse(My.MySettings.Default.Interval).TotalSeconds
Dim date3 As Date = date1.AddSeconds(toadd)
Console.WriteLine(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss:fff") & " > Timer restarted. Next batch process {0}", date3.ToString(dateFormat))
Await Task.Delay(tmr_repeat)
Loop
Catch ex As Exception
End Try
End Sub
Currently whenever I press Ctrl-C or accidently pressing Enter key 2 times, it will suddently terminate the console even the console is on doing some async loop task. I have try some code but not works and even I stuck on placing the code and merge with my ConsoleStartup Sub
What I have tried:
Sub Main(ByVal args() As String)
Dim t As Task = MainAsync(args)
t.Wait()
End Sub
Private Function MainAsync(ByVal args() As String) As Task
ShowConsole()
MaximizeConsole()
Trace.Listeners.Clear()
Dim twtl As New TextWriterTraceListener(AppDomain.CurrentDomain.BaseDirectory & "out.txt")
twtl.Name = "TextLogger"
twtl.TraceOutputOptions = TraceOptions.ThreadId Or TraceOptions.DateTime
Dim ctl As New ConsoleTraceListener(False)
ctl.TraceOutputOptions = TraceOptions.DateTime
Trace.Listeners.Add(twtl)
Trace.Listeners.Add(ctl)
Trace.AutoFlush = True
Trace.WriteLine("Program started at " & DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss:fff"))
ConsoleStartup()
Console.ReadKey()
End Function
I dont know why you've tagged your question with C#, because your code clearly isnt ... anyway
have you looked at SetConsoleCtrlHandler function (Windows)[^] ?
I have a console process in c# that uses Control-C to 'trip' an event and do more work or in another case to raise a signal to a BackgroundWorker that it should stop what its doing .. in both cases, and this is where it gets into a grey area, I then continue to do work, even allowing Control-C to be used again (as opposed to a comment I saw, suggesting that the handler had to do its work quickly else the program would become unstable .. I guess the handler does do its work quickly - raises an event, but, the Control-C/Control-Break etc is trapped) and I can do whatever afterwards
Im pretty sure there's VB.Net code showing how to use SetConsoleCtrlHandler - this maybe AddressOf.com : Console Event Handling[^]
[edit] sorry, this only answers part of your question, I'd have to think about the keyboard part... at a pinch I'd be thinking of setting a flag to say 'Im working', then when the flag is 'unset', ie work has finished, flushing the keyboard buffer [/edit]
I'm using this code and its preventing any key to exit from console even Ctrl-C key were pressed.
Private bExit As Boolean Private input As String Sub Main(ByVal args() As String) bExit = False Console.TreatControlCAsInput = True MainFunctionStartHere 'My main task function will be called here Do input = Console.ReadLine() 'While function is running, this will 'start capturing key If input = "P" Then bExit = True Trace.WriteLine("Exiting!") Task.Delay(3000) End If Loop While (Not (bExit)) End Sub
I don't know if there is any other way that works on my code
这篇关于当控制台运行异步任务时,阻止控制台通过ctrl-C终止或多按回车键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!