Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pause a BackgroundWorker? Or something similar

I was using a BackgroundWorker to download some web sites by calling WebClient.DownloadString inside a loop. I wanted the option for the user to cancel in the middle of downloading stuff, so I called CancelAsync whenever I found that CancellationPending was on in the middle of the loop.

But now I noticed that the function DownloadString kinda freezes sometimes, so I decided to use DownloadStringAsync instead (all this inside the other thread created with BackgroundWorker). And since I don't want to rewrite my whole code by having to exit the loop and the function after calling DownloadStringAsync, I made a while loop right after calling it that does nothing but check for a variable bool Stop that I turn true either when the DownloadStringCompleted event handler is called or when the user request to cancel the operation.

Now, the weird thing is that it works fine on the debug version; but on the release one, the program freezes in the while loop like if it were the main thread.

like image 729
Juan Avatar asked Jun 12 '10 08:06

Juan


People also ask

How do I pause my background worker?

if you want to pause and resume a BGW, split your task into smaller packets (or put the needed values (like a counter variable/state) into e. Result), stop the BGW at a safe point and in the RunWorkerCompleted event, dispose the worker, instanciate it again (or a second BGW) and fire it up when needed.

What is the difference between BackgroundWorker and thread?

A BackgroundWorker is a ready to use class in WinForms allowing you to execute tasks on background threads which avoids freezing the UI and in addition to this allows you to easily marshal the execution of the success callback on the main thread which gives you the possibility to update the user interface with the ...

How does DoWork pass parameters to BackgroundWorker?

You can send a parameter to the background operation using the RunWorkerAsync() method. You can receive this parameter by using the Argument property of the instance of DoWorkEventArgs in the DoWork event handler then you cast it to use it in the background operation.

What is a BackgroundWorker in C#?

A BackgroundWorker component executes code in a separate dedicated secondary thread. In this article, I will demonstrate how to use the BackgroundWorker component to execute a time-consuming process while the main thread is still available to the user interface.


1 Answers

Sounds to me you are busy-waiting with a while loop. You should use event signaling instead, eg. a WaitHandle. A busy-waiting loop in release mode might very well consume all your cpu, giving a feeling of a freeze.

Signal the WaitHandle in DownloadStringCompleted or if the user cancels the download.

Check the MSDN docs on the WaitHandle class. There's also an example there.

like image 77
Mikael Svenson Avatar answered Nov 02 '22 03:11

Mikael Svenson