gpt4 book ai didi

c# - 有没有一种干净的方法可以在 BackgroundWorker 中检查取消请求,而无需一遍又一遍地重新键入相同的代码?

转载 作者:太空狗 更新时间:2023-10-29 23:14:21 24 4
gpt4 key购买 nike

如果我想定期检查是否有取消请求,我会在我的 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;
}

...
}

最佳答案

使用 while 循环和委托(delegate)

将您的任务添加到委托(delegate)列表中,然后循环测试您的条件。

您可以使用 Action 自定义委托(delegate)来简化此任务(参见: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;
}

关于c# - 有没有一种干净的方法可以在 BackgroundWorker 中检查取消请求,而无需一遍又一遍地重新键入相同的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26629852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com