TimeWorker Timeout

I use WPFSystem.ComponentModel.BackgroundWorker in my application .

How to set a timeout for BackgroundWorker?

+5
source share
2 answers

My suggestion is as follows

backgroundworker1 does the work - it accepts the cancellation, so you can stop it.

backgroundworker2 loops when the wait time is on hold and the wait time ends.

If backgroundworker1 still works, RunWorkerCompletethis BackgroundWorkeris killed by backgroundworker1 ..

, backgroundworker1, , .

+4

BackgroundWorker -, . , , CancellationPending, . -, . .

    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
            }
        }
    }

, , -, - , - #. BackgroundWorker.

+4

All Articles