how to cancel background worker after specified time in c#

百般思念 提交于 2019-12-12 10:50:05

问题


how to cancel background worker after specified time in c# or cancel not responding background worker.


回答1:


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

In order for a System.ComponentModel.BackgroundWorker thread to support cancellation, you need to set the WorkerSupportsCancellation property to True before starting the thread.

You can then call the .CancelAsync method of the BackgroundWorker to cancel the thread.




回答2:


BackgroundWorker does not have support either case. Here is the start of some code to support those 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 );
        }
    }
}


来源:https://stackoverflow.com/questions/1341488/how-to-cancel-background-worker-after-specified-time-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!