开发者

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 e开发者_开发技巧ither 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.


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.


nice topic, i used In my background worker process a double while

 int icounter = 1;
 while (icounter < SomeListInventory.Count)
            {
                while (pauseWorker == false)
                { 
                    //-----------------------
                    //DO SOME WORK
                        icounter++;
                    //-----------------------
                }
            }

And i have a button pause, that when i press it, pauseWorker (Global variable or property) becomes true and loops in the first while only, without increasing the icounter, and when i make the pauseworker=false again the process continues

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜