Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout for BackgroundWorker

I am using System.ComponentModel.BackgroundWorker in my WPF application.

How can I set timeout for BackgroundWorker ?

like image 786
Armen Khachatryan Avatar asked Jul 03 '12 14:07

Armen Khachatryan


2 Answers

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.

like image 171
BugFinder Avatar answered Sep 29 '22 01:09

BugFinder


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.

like image 42
vossad01 Avatar answered Sep 29 '22 01:09

vossad01