I have went over dozens of question and tutorial but ended up with nothing so I hope to get help of you guys.
I have a BW, doing some heavy work (rading up services, saving them into a file).
BW is initialized at run time, and fired up with button click. This works perfectly, but thing is it works non-stop or till event btn_cancel
get's clicked which stops the BW.
What I want to achieve is to start my bw_doWork
again with button click, but work only for specified period of time. For the first time, it takes up to 30 secs to doWork()
to finish, then around 10. I have tried to use Stop Watch but with no success so far.
My code so far looks like this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Do not access the form's BackgroundWorker reference directly.
// Instead, use the reference provided by the sender parameter.
long targetTime = (long) e.Argument;
Stopwatch sw = new Stopwatch();
if (targetTime > 0)
{
sw.Start();
}
while (true)
{
if ((targetTime > 0) && (sw.ElapsedMilliseconds >= targetTime))
{
BackgroundWorker bw = sender as BackgroundWorker;
while (!bw.CancellationPending)
{
GetServicesToFile();
}
sw.Reset();
sw.Start();
}
}
}
btn_Click
private void btnServiceLoad_Click(object sender, EventArgs e)
{
// sw.Start();
if (backgroundWorker1.IsBusy != true)
{
this.backgroundWorker1.RunWorkerAsync();
}
ReadServicesFromFile();
}
Managed this with a
System.Windows.Forms.Timer
which starts along withBackgroundWorker
, whose delay you initialise freely, and whose firstTick
event cancelsBackgroundWorker
. You can also cancel with a button. Does that help?GUI code for file
.Designer.cs
available at http://ideone.com/PcvCRB