Send a backgroundworker to sleep while checking for cancellation

后端 未结 3 845
悲&欢浪女
悲&欢浪女 2021-01-06 01:34

I have a background worker which updates the GUI on a regular basis via ReportProgress.

The update occurs at regular intervals, every 5 seconds for example, or it c

3条回答
  •  情歌与酒
    2021-01-06 01:47

    You can use a ManualResetEvent to both allow your thread to wait without polling and to allow another thread to wake it up any anytime.

    The ManualResetEvent as well as any of the other thread synchronization objects has a WaitOne method that can wait for the event to be set or for a time out. So normally you can have WaitOne wait for the amount you want to wait for (which will work like a Thread.Sleep) but the main thread can wake up the background thread at any time.

    ManualResetEvent backgroundWakeEvent = new ManualResetEvent(false);
    ....
    bkgwk.CancelAync();
    backgroundWaitEvent.Set();
    ....
    backgroundWakeEvent.WaitOne(5000);
    
    if (bkgwk.CancellationPending)
    {
        cancelled = true;
        e.Cancel = true;
        bkgwk.Dispose();
        break;
    }
    

提交回复
热议问题