C# console application randomly waits for input - c#

i made an app and sometimes it just pauses until I press a key.
i do not use any code which requiereres any input or interaction (such as readline or readkey).
this randomly happens like 1 in 20 times after Thread.Sleep and after you press any key it continues to work perfectly.
if (Convert.ToInt64(timetotask[0]) > 0)
{
Thread.Sleep(Convert.ToInt32(timetotask[0]));
}
else
{
mylog.log("Task was in the past, executing it now");
}
int currentbid = placebid(task.itemid, bid, driver[Convert.ToInt32(task.account)]);
the first line of placebid is console.writeline("mystring") so i do not see anything what could cause this behaviour.
Does it have something to do with debug mode?
thanks for help

This could be obvious but if pressing a key in the console makes the application resume, it is most likely you managed to pause the app via the console by pressing a key.
When it is sleeping do you ever press a key to check if it has paused? Then eventually the sleep ends as it matches the rule and then when you next press a key it unpauses the program...
Michael

Related

Listen for key press .NET console app does not stop running application

I have been researching in how to stop a console application when pressing esc (or any key really.
I ran into this solution
Listen for key press in .NET console app
Now, I was trying to apply it to my case:
I should stop my console app, which is a loop, when I press any key.
Coming from the solution provided in the topic above, I added my own part as follows:
Console.WriteLine("Press ESC to stop");
do {
while (! Console.KeyAvailable) {
foreach (var station in WeatherStations.station)
{
var stationAirParams = station.value?.FirstOrDefault();
Console.WriteLine(
station.name + " " + (stationAirParams == null
? ""
: stationAirParams.value)
);
Thread.Sleep(100);
}
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
That said... why isn't the loop stopping?
Your approach uses polling in a single thread, and it is not event driven.
The inner loop won't stop on key press. It will simply finish its work before the code checks for key press for the first time in the outer loops.
Move an abort condition like the following
if(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)
{
break;
}
to the innermost loop.
There is another answer here which shows how to spawn a background thread to do the work whilst waiting for a keypress to exit on the main thread.

Stop Console Application from pausing on Pause Evemt

I've implememted a small Console Application that checks how long a programm is running. I then tried to run the application and everything is working fine. However then i hit (by accident) the "pause" key on my Keyboard and the programm stopped executing.
Is there a way to handle this event in a Console Application to suppress this pausing?
Update:
class Program
{
static void Main(string[] args)
{
while (true)
{
Thread.Sleep(2000);
var p = Process.GetProcessesByName("wineks");
if (p != null)
{
Console.WriteLine("Found Process. Close it please");
Console.ReadKey();
}
}
}
}
That is basically my code. It is only asking the user to close a specific process. If I know hit the Pause Button on my Keyboard before I see the message, the message will never appear because the application freezes and seems like paused.
From browsing in the Internet I know that the key I press has the Name Pause and the key is sending some kind of Event or Signal to the Console.
Actually the Console does not have a way to raise KeyPress events , you can however try some looped approach to handle any key press done accidentally . Refer to this stackoverflow question here
Try inserting these lines before GetProcessByName
if (Console.KeyAvailable)
{
if (ConsoleKey.Pause == Console.ReadKey().Key)
continue;
}

How to break a loop with user input?

I want to break or pause a do/while loop if a user presses a key in the console. I have tried ReadLine or ReadKey but then my program stops and it is waiting for input, but I only want my program to stop after user input.
My code:
do
{
//do some code until user input
Console.WriteLine("for settings: Press 's'");
ConsoleKeyInfo cki;
cki = Console.ReadKey(); // here the program stops and waits for input but I don't want it
if (cki.Key.ToString() == "S")
{
Console.WriteLine("SETTINGS");
}
} while (true);
Check out Console.KeyAvailable this will be true when a user presses a key. When it is true then you can do Console.ReadKey()
You won't be able to have your program do that easily, that is actually doing 2 things at once 1) waiting on input (what readline/readkey does) and 2) continuing the work at the same time.
You could do this with multithreading by launching having your logic executing on one threat and the waiting on user input on another thread, then communicating between threads when user input happens but based on your question this is probably a too compelx answer, i will gladly write a sample but i think it is more likely to confuse than to help.

C# Console.In.Peek(); returns endless results after initial key press

I'm trying to create a thread which I check for key presses in a console application. The idea being if no keys are pressed for 10 minutes the user is logged out.
I spawn this little thread where I try to use Console.In.Peek(); to get a key press without reading the key so the main thread can actually ReadKey / ReadLine issue free. However, I am finding that upon pressing the very first key Console.In.Peek(); stops blocking and that loop goes over and over without obstruction.
Any ideas why Console.In.Peek(); stops blocking after the first key press and any ideas how to fix it? Thanks so much!
public static void AuthTimer()
{
while (true)
{
Console.In.Peek();
Thread.Sleep(1000);
//Console.ReadKey();
Console.WriteLine("auth timer");
if (Authentication.Authenticated == true)
{
Authentication.AuthTime = DateTime.Now;
}
}
}
EDIT EDIT EDIT
Thanks to the comments here by the fine folks on Stackoverflow I gave up on Console.In.Peek() and switched to
if (Console.KeyAvailable == true)
It doesn't take the key out of the stream and seems to block until a key is pressed so it effectively solves my issue! Thanks everyone for the comments.

trapping a key before it gets to the Console

THE SETTING:
A Console program, in .net
I am using readkey in a loop, which rewrites to the same line on the screen (Console.setCursorPosition)
however, if I type Enter, the Console pushes the text upwards, which is the usual command line behaviour.
THE QUESTION:
Is it possible to trap a key press (that Enter), so that my program will get the key, but the Console does not?
The environment is Linux, with Mono (and the program is supposed to be cross platform). so low level windows driver intercepting is not an option.
PS: I know the method of clearing and redrawing everything. I would like to know if my question is possible.
Thank you for any information
after modifying code found here https://stackoverflow.com/a/8898251/1951298 I came to something that may help you, you see that when user pushes Enter the cursor doesn't increment, and nothing is written into console
ConsoleKeyInfo keyinfo;
int left, top=0;
do
{
left = Console.CursorLeft;
top = Console.CursorTop;
keyinfo = Console.ReadKey(true);
if(keyinfo.Key.ToString().Equals("Enter"))
Console.SetCursorPosition(left,top-1);
else
Console.WriteLine(keyinfo.Key + " was pressed");
}
while (keyinfo.Key != ConsoleKey.X);
Console.ReadKey(true) should read the key but not show it.
You should intercept the key press. MSDN Documentation
var PressedKey = Console.ReadKey(true)

Categories