在迭代中Async return - Task ContinueWith在ForEach中
本文关键字:ForEach ContinueWith Task return 迭代 Async | 更新日期: 2023-09-27 18:01:24
目的是使用一组关键字搜索特定的内容,但要进行响应性搜索,而不是等待函数直接返回内容。
下面的代码在keywords参数中考虑最多3个关键字项,但我需要循环遍历关键字,直到搜索完所有关键字(除非之前返回的是正结果):
public void SearchForSomething(params string[] keywords)
{
var index = -1;
index = index + 1;
if (keywords != null && keywords.Any())
{
var successTask = this.Search(keywords[index]);
successTask.ContinueWith(
task =>
{
if (!task.Result)
{
index = index + 1;
if (index < keywords.Count())
{
var successTask2 = this.Search(keywords[index]);
successTask2.ContinueWith(
task2 =>
{
if (!task2.Result)
{
index = index + 1;
if (index < keywords.Count())
{
var successTask3 = this.Search(keywords[index]);
successTask3.ContinueWith(
task3 =>
{
if (!task3.Result)
{
this.NotifyNada(keywords);
}
});
}
else
{
this.NotifyNada(keywords);
}
}
});
}
else
{
this.NotifyNada(keywords);
}
}
});
}
else
{
this.NotifyNada(keywords);
}
}
如何搜索说50个关键字字符串?
- 异步,但仍按顺序(不是并行)
我提到您可能能够使用async/await提出一个简单的解决方案。我没有详细研究过代码,但在我看来,这就是你正在做的事情:
public async Task SearchForSomething(params string[] keywords)
{
foreach (var keyword in keywords)
{
if (await Search(keyword))
{
// If we have a result, we return
return;
}
}
// If we didn't find, notify?
NotifyNada(keywords);
}