C
C#16mo ago
SWEETPONY

✅ can Thread.Sleep affect performance?

namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press any key for one second...");

DateTime endWaitTime = DateTime.Now.AddSeconds(1);
while (DateTime.Now < endWaitTime)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true);
Console.WriteLine($"You pressed: {key.KeyChar}");
break;
}
Thread.Sleep(50); // a short pause to reduce the CPU load
}

Console.WriteLine("Continuation of the program execution...");
}
}
}
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press any key for one second...");

DateTime endWaitTime = DateTime.Now.AddSeconds(1);
while (DateTime.Now < endWaitTime)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true);
Console.WriteLine($"You pressed: {key.KeyChar}");
break;
}
Thread.Sleep(50); // a short pause to reduce the CPU load
}

Console.WriteLine("Continuation of the program execution...");
}
}
}
Should I add Thread.Sleep(50); in this situation? Is it worth it?
9 Replies
Jimmacle
Jimmacle16mo ago
why wouldn't you just sleep the thread for one second? i mean the code should work fine, but just be aware that both DateTime and Thread.Sleep aren't very precise in terms of timing things
SWEETPONY
SWEETPONYOP16mo ago
i read that constant polling of the Console status... may cause excessive CPU load so I decided to add Thread.Sleep but I don't know is it really helps is it possible to test?
Jimmacle
Jimmacle16mo ago
look at your CPU usage with and without it
SWEETPONY
SWEETPONYOP16mo ago
ok I will try to use BenchmarkDotNet, maybe it will help
Jimmacle
Jimmacle16mo ago
that doesn't measure CPU usage afaik it just measures how long calls take, memory allocation, etc benchmarking a method that waits for one second will show you that it takes one second
SWEETPONY
SWEETPONYOP16mo ago
hmm okay
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View
SWEETPONY
SWEETPONYOP16mo ago
can you show an example?
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server