是否有一种干净的方法来检查BackgroundWorker中的取消请求,而无需一遍又一遍地重新键入相同的代码?

时间:2014-10-29 12:03:02

标签: c#

如果我想定期检查是否有取消请求,我会在DoWork事件处理程序中不断使用下面的代码:

    if(w.CancellationPending == true)
    {
        e.Cancel = true;
        return;
    }  

有没有一种干净的方法来检查C#中BackgroundWorker的取消请求,而不是一遍又一遍地重新输入相同的代码?

请参阅以下代码:

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    ...

    BackgroundWorker w = sender as BackgroundWorker;

    if(w.CancellationPending == true)
    {
        e.Cancel = true;
        return;
    }

    some_time_consuming_task...

    if(w.CancellationPending == true)
    {
        e.Cancel = true;
        return;
    }

    another_time_consuming_task...

    if(w.CancellationPending == true)
    {
        e.Cancel = true;
        return;
    }

    ...
}

1 个答案:

答案 0 :(得分:5)

使用while循环并委派

在委托列表中添加您的任务,然后循环测试您的状况。

您可以使用Action自定义委托来简化此任务(请参阅:http://msdn.microsoft.com/en-us/library/system.action(v=vs.110).aspx

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    List<Action> delegates = new List<Action>();
    delegates.add(some_time_consuming_task);
    delegates.add(another_time_consuming_task);

    BackgroundWorker w = sender as BackgroundWorker;    
    while(!w.CancellationPending && delegate.Count!=0)
    {
        delegates[0]();
        delegates.remove(0);
    }

    if(w.CancellationPending)
        e.Cancel = true;
}