迭代中的异步 return - ForEach 中的任务 ContinueWith
Async return inside an iteration - Task ContinueWith inside ForEach
目的是用一堆关键字搜索特定的东西,但要被动地做,而不是等待函数直接 return 东西。
以下代码考虑了 keywords 参数中最多 3 个关键字项,但我需要循环遍历关键字,直到搜索完所有关键字(除非之前 return 编辑了肯定结果):
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);
}
}
如何搜索 say 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);
}
目的是用一堆关键字搜索特定的东西,但要被动地做,而不是等待函数直接 return 东西。
以下代码考虑了 keywords 参数中最多 3 个关键字项,但我需要循环遍历关键字,直到搜索完所有关键字(除非之前 return 编辑了肯定结果):
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);
}
}
如何搜索 say 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);
}