var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));
new Thread(async () =>
{
try
{
while (await timer.WaitForNextTickAsync().ConfigureAwait(false))
{
... do some things
}
}
catch (OperationCanceledException)
{
}
})
{
IsBackground = true,
}
.Start();
Every 5 minutes I have to do some things in the background thread. For some reason in some random time I get 300% cpu usage. Something wrong with my code? Thanks.
Yes, there is something wrong with this code, but fixing it will not solve the CPU over-utilization problem. The wrong thing is that you pass an asynchronous delegate to the
Threadconstructor. TheThreadclass does not expect anasyncdelegate in the constructor, so the delegate isasync void, which is something to avoid. You can learn why this is pointless from the answer in this question:You can fix this by replacing the
new Thread(async () =>withTask.Run(async () =>. TheTask.Runmethod understands async delegates, and will give you back aTaskthat you can laterawait, or query for its completion and potentialException. In case you want to keep the existingasync voidsemantics, meaning that in case of an unhandled exception you want your program to crash, then replace thenew Thread(async () =>withThreadPool.QueueUserWorkItem(async _ =>.As for the reason for the CPU spikes, it is hidden in the
... do some thingscode. We don't know what this code does, so we can't help you fix it.