![](/img/trans.png)
[英]Cannot convert async lambda expression to delegate type 'Func<UIAccessibilityCustomAction, bool>
[英]Cannot convert async lambda expression to delegate type 'Func<bool, string, bool>'
我收到以下代碼的錯誤。
public async Task<bool> FlushUrlAsync(Uri url, bool recursive, CancellationToken token = default(CancellationToken))
{
_serverPortsConfig.CacheServerPorts
.Select(cacheServerPort => $"http://{url.Host}:{cacheServerPort}{url.AbsolutePath}")
.Aggregate(true, (current, memoryCacheUrl) => current && await FlushUrlAsync(recursive, memoryCacheUrl)); //<--- produces the next error:
// Cannot convert async lambda expression to delegate type
// 'Func<bool, string, bool>'. An async lambda expression may return
// void, Task or Task<T>, none of which are convertible to
// 'Func<bool, string, bool>'.
}
該方法調用以下函數
private async Task<bool> FlushUrlAsync(bool recursive, string memoryCacheUrl)
{
return await someMagic(); //for clearity I removed the code.
}
它看起來很像: 將異步 lambda 表達式轉換為委托類型 System.Func<T>? ,然而,有解決方案不會/不能讓它為我工作。
我有:
var result = true;
foreach (var cacheServerPort in _serverPortsConfig.CacheServerPorts)
{
var memoryCacheUrl = $"http://{url.Host}:{cacheServerPort}{url.AbsolutePath}";
result = result && await FlushUrlAsync(memoryCacheUrl, recursive);
}
return result;
然后 resharper 給了我提供的代碼,但只是添加 async 關鍵字不起作用。
.Aggregate(true, async (current, memoryCacheUrl) => current && await FlushUrlAsync(recursive, memoryCacheUrl));
會給我錯誤:異步方法的返回類型必須是 void、task 或 Task。
有任何想法嗎?
我個人會使用foreach
實現,但回答具體問題。
如果沒有async
則使用的Aggregate
重載具有以下簽名:
bool Aggregate<bool, string>(bool seed, Func<bool, string, bool> func)
注意func
參數 - 它是一個接收bool
和返回bool
string
的方法。 重要的是第一個參數的類型與結果的類型以及seed
參數的類型相同。
由於async
lambda必須返回Task
派生對象。 你需要一個bool
結果,所以讓它替換為Task<bool>
:
Task<bool> Aggregate<bool, string>(Task<bool> seed, Func<Task<bool>, string, Task<bool>> func)
這導致以下解決方案:
return await _serverPortsConfig.CacheServerPorts
.Select(cacheServerPort => $"http://{url.Host}:{cacheServerPort}{url.AbsolutePath}")
.Aggregate(Task.FromResult(true), async (current, memoryCacheUrl) =>
await current && await FlushUrlAsync(recursive, memoryCacheUrl));
將 ContinueWith 與 TaskContinuationOptions 一起使用,
Func<Exception, bool> handlerFunc = (Exception ex) =>
{
ex.HandleExceptionAsync().ContinueWith(async (result) =>
{
// all await operations can be called here
}, System.Threading.Tasks.TaskContinuationOptions.OnlyOnRanToCompletion);
return true;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.