I am using System.ComponentModel.BackgroundWorker
in my WPF application.
How can I set timeout for BackgroundWorker
?
My suggestion is following
backgroundworker1 does the work - it accepts cancellation so you can make it stop.
backgroundworker2 does a loop while the time out is pending, and on time out completes.
If backgroundworker1 is still running, the RunWorkerComplete
of this BackgroundWorker
, kills off backgroundworker1..
This should also accept cancellation so that if backgroundworker1 completes and this is still running, you can cancel it.
BackgroundWorker does not directly support a timeout, but it does support cancellation. This will work well if the work being done is an a loop or other structure where you can periodically check the CancellationPending member to then abort. You will need some thing else to tell the background worker to cancel after the timeout. Here I used an async call of an action.
static void Main( string[] args )
{
var bg = new BackgroundWorker { WorkerSupportsCancellation = true };
bg.DoWork += LongRunningTask;
const int Timeout = 500;
Action a = () =>
{
Thread.Sleep( Timeout );
bg.CancelAsync();
};
a.BeginInvoke( delegate { }, null );
bg.RunWorkerAsync();
Console.ReadKey();
}
private static void LongRunningTask( object sender, DoWorkEventArgs eventArgs )
{
var worker = (BackgroundWorker)sender;
foreach ( var i in Enumerable.Range( 0, 5000 ) )
{
if ( worker.CancellationPending )
{
return;
}
else
{
//Keep working
}
}
}
If this doesn't really fit what your are trying to accomplish you may be interested in the generic timeout solutions found at Implementing a timeout on a function returning a value or Implement C# Generic Timeout. You could use those inside the BackgroundWorker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With