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.
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.