Reputation: 41
I am a newbie in .net world so i am facing some problem,please help me out, here is one of them,I have a for loop and i have a backgroundWorker control and a progressBar Control and also have 1 button that id:"btnPause".So my requirement is when my form will load the peogressbar will show the progress how much it has completed ,whenever i click on the button(btnPause) the button text need to b change and set the text as pause, then whenever i clicked again on that button it need to be resume from the value it got paused.Please help me.
Thanks in advance.
Upvotes: 1
Views: 2181
Reputation: 2760
Try to use this
class MyWorkerClass
{
volatile bool m_bPaused = false;
// Public property to control worker execution
public bool Paused
{
get { return m_bPaused; }
set { m_bPaused = value; }
}
long ThreadFunc (BackgroundWorker worker, DoWorkEventArgs e)
{
...
// While Paused property set to true
while (m_bPaused)
{
// Pause execution for some time
System.Threading.Thread.Sleep (100);
}
}
}
Upvotes: 0
Reputation: 13494
My approach to this would be to use a boolean flag to let me know whether or not the operation is paused (and perhaps a second one letting me know whether or not the operation is cancelled). When the user presses the pause button, you set the IsPaused
flag to true so that when the worker begins processing the next item, it can check this flag and know to go into a wait state.
There are a few ways to keep the BackgroundWorker in this paused state. My approach would be to use a ManualResetEvent. This allows the BackgroundWorker thread to enter a sleep state and come out when the event is set. I think this is better than using a while loop with a sleep body because the thread stays asleep until the event is set, rather than waking up to check if it should still be asleep. When the user wishes to continue, it can set this event and let the Background worker continue.
So the code would look a little like this:
private void backgroundWorker_doWork(object sender, DoWorkEventArgs args)
{
//Initialize any pre-work stuff here.
while(!finished)
{
if (Paused)
m_evtPause.WaitOne();
if (Cancelled)
break;
//lengthy thread procedure code.
}
}
Upvotes: 1