Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
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:
C#
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:-
VB.NET
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
Posted
Updated 23-Aug-16 6:09am

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]
 
Share this answer
 
v2
Comments
Luiey Ichigo 23-Aug-16 10:50am    
Hi Garth,

I'm opening to both C# and Visual Basic. I'm writing in Visual Basic but I can translate those C# and apply on my VB. That's why I'm tagging both language. Currently I'm applying one code. Which actually catch any character and filter it for exit purposes. And it catch combine key also.


Private bExit As Boolean
Private input As String
Sub Main(ByVal args() As String)
bExit = False
Console.TreatControlCAsInput = True
StartTaskHere 'My main task function will be called here
Do
input = Console.ReadLine()
If input = "P" Then
bExit = True
Console.WriteLine("Exiting!")
Task.Delay(3000)
End If
Loop While (Not (bExit))
End Sub
I'm using this code and its preventing any key to exit from console even Ctrl-C key were pressed.

VB
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
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900