views:

199

answers:

2

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). An since and 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 checks 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.

A: 

Send your while loop that is checking for the cancelation to sleep for a short while (some ms). This well free up the CPU runtime for other threads and processes.

Mark
Busy waiting is bad practice.
Mikael Svenson
I know and I didn't know that there was something like a WaitHandle in C#/.Net (always new things to learn :-)), but sometimes polling is the only solution and then one should make sure that the process polling only checks once and then gives up the CPU time (in Linux its the yield() function) given to the thread/process by the OS.
Mark
The WaitHandles can also be used with a timeout, so that would prevent polling :) (And I have used my share of busy waiting until I got wiser.. hehe)
Mikael Svenson
+2  A: 

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.

Mikael Svenson
WaitHandle works just perfect. Thank you!
jsoldi