I have simple WPF application where I am doing some processing within a Task
and updating the UI with CPU usage, elapsed time and thread count, using a Dispatcher.Timer
.
Task.Run(() =>
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 700);
dispatcherTimer.Start();
}).Wait();
Task process = new Task(() =>
{
sw.Start();
ConvertToGrayscale(sourcePath, destinationPath);
CheckUniqueColorPixels(sourcePath);
});
process.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
lblElapsedTime.Content = Math.Round(sw.Elapsed.TotalSeconds, 1);
lblCPUUsage.Content = getCPUCounter();
lblThreadCount.Content = Process.GetCurrentProcess().Threads.Count;
}
private double getCPUCounter()
{
double cpuUsage = 0;
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
cpuUsage = Math.Round(cpuCounter.NextValue(), 2);
Task.Delay(1500).ContinueWith(_ =>
{
cpuUsage = Math.Round(cpuCounter.NextValue(), 2);
});
return cpuUsage;
}
This works fine. But when I use Parallel.Invoke
Task process = new Task(() =>
{
sw.Start();
Parallel.Invoke(
() => this.ConvertToGrayscaleP(sourcePath, destinationPath),
() => this.CheckUniqueColorPixelsP(sourcePath));
});
process.Start();
My CPU usage always shows 100, constantly, and never updates. I am suspecting there is some problem in getCPUCounter()
as the other values (elapsed time and thread count) gets updated though.
I tried using Thread.Start()
explicitly instead of Task.Run()
but that did not work.
Please let me know if I can give some more details.
Thanks.