How to cancel background worker after specified time in C #

how to cancel a background worker after a specified time in C # or cancel a non-responding background worker.

+4
source share
2 answers

Check out this tutorial: http://www.albahari.com/threading/part3.aspx

In order for the System.ComponentModel.BackgroundWorker stream to support cancellation, you need to set the WorkerSupportsCancellation property to True before the stream starts.

You can then call the .CancelAsync method for BackgroundWorker to cancel the stream.

+3
source

BackgroundWorker does not support any of these cases. Here is the beginning of some code to support these cases.

class MyBackgroundWorker :BackgroundWorker { public MyBackgroundWorker() { WorkerReportsProgress = true; WorkerSupportsCancellation = true; } protected override void OnDoWork( DoWorkEventArgs e ) { var thread = Thread.CurrentThread; using( var cancelTimeout = new System.Threading.Timer( o => CancelAsync(), null, TimeSpan.FromMinutes( 1 ), TimeSpan.Zero ) ) using( var abortTimeout = new System.Threading.Timer( o => thread.Abort(), null, TimeSpan.FromMinutes( 2 ), TimeSpan.Zero ) ) { for( int i = 0; i <= 100; i += 20 ) { ReportProgress( i ); if( CancellationPending ) { e.Cancel = true; return; } Thread.Sleep( 1000 ); //do work } e.Result = "My Result"; //report result base.OnDoWork( e ); } } } 
0
source

All Articles