I have a .net core 3.1 application that is taken 15-20% of the CPU when running on Raspbian (Rasp Pi 3). When it runs inside Visual Studio on my Windows PC the CPU graph shows between 0-1%
The application itself is fairly simple, it’s a C# console app with System.IO.Ports and RabbitMQ installed from NuGet.
Main() first sets up the serial port and assigns mySerialFunc() to the DataReceived event. It also sets up RabbitMQ and likewise assigns myRabbitMQ() to a consumer.Received event. After that main() drops into a while loop
static Main(string[] args)
{
// setup code and events here
// ……
while (runFlag)
{
// Nothing in the loop, just keep the app running
// Generates 100% CPU
}
}
Like this on the windows all was good, but on Raspbian the app would take 100% CPU. Ouch…
So I changed the app and added in System.Threading and System.Threading.Tasks
So my while loop now looks like this
Static async Task Main(string[] args)
{
// setup code and events here
// ……
while (runFlag)
{
// This generate 15-20% CPU
await Task.Delay(1000);
}
}
This has calmed the CPU down to 15-20%
Clearly the high CPU is caused by running the while continuously, so what’s the best way of doing this please?
I basically have two functions that run when something happens on the serial port or a RabitMQ message is received. When no events are happening I simple need the program to continuously run until the runFlag is set to false.
But at the same time not take up too much CPU, after all its running on a Rasp Pi.
Any ideas?
# # UPDATE # #
Many thanks for your comments on the subject.
I have since managed to get my Application running at 0.3-1% CPU by changing the continuous loop as per the code below.
using System;
using System.Threading;
namespace daemonTest_withThreadSleep
{
class Program
{
// Define a daemonRunFlag for continous running
static bool daemonRunFlag = true;
static readonly CancellationTokenSource tokenSource = new CancellationTokenSource();
static void Main(string[] args)
{
// Add event to handle process exits, such as HUP signals.
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
// Add the setup code here
// Add the event functions here
// Start the Daemon Running
Console.WriteLine("Starting Daemon");
while ((daemonRunFlag) && (!tokenSource.Token.IsCancellationRequested))
{
// This generates 0.3-1% CPU
System.Threading.Thread.Sleep(1000);
}
Console.WriteLine("Ending Daemon");
}
private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
// Function is called because of an HUP signal.
// Set the haLogHandle daemonRunFlag to false.
daemonRunFlag = false;
// cancel the received token.
tokenSource.Cancel();
}
}
}
The above code also includes handling of HUP signals as the code is running on Raspbian.
I'm note sure why System.Threading.Thread.Sleep(1000)
produces lower CPU usage compared to await Task.Delay(1000)
Any ideas?