I have a background worker which updates the GUI on a regular basis via ReportProgress.
The update occurs at regular intervals, every 5 seconds for example, or it could be 20 seconds. In order to perform the update at set times I send the worker process to sleep for the duration and when it wakes it updates the GUI with new information.
The worker supports cancellation, and outside of sleeping it cancels correctly.
I want to be able to invoke the cancellation during the wait period, however sending the thread to sleep makes this impossible.
I assume I’ll have to invoke a loop and check for the cancellation as part of the loop to simulate the thread sleep.
What is the best method for achieving this, my timing is completely off with my attempt.
long counter = 0;
long sleepfor = timelinespeed*1000;
int timelinespeed = 10;
while (counter != sleepfor)
{
Thread.Sleep(1);
counter++;
if (bkgwk.CancellationPending)
{
cancelled = true;
e.Cancel = true;
bkgwk.Dispose();
break;
}
}
You’re going down the wrong path.
Sleep()on any thread. Certainly not for more than a few ms.Sleep(1)in a busy-wait for 5 seconds is a big waste of CPU. You are hurting your other threads. At the very least consider upping it toSleep(100)or so. Find the max delay you will allow for your Cancel.As a solution: Use a Timer. You have a periodical task, use the right tool.
Use
System.Threading.Timerfor ThreadPool based background work. Update the GUI through Dispatcher.Invoke().Use the
Dispatcher.Timerto execute small (under 0.1 sec) portions of work on the Main thread. You can directly update the GUI.