将异步函数作为参数传入另一个异步函数时触发BC42358警告的问题
BC42358警告原因及代码正确性解析
你编写了用于缓存网络数据的异步函数downloadStringAndCacheAsync,期望传入一个返回Task(Of String)的函数,在函数内部await该Task。但调用时触发了BC42358警告,疑惑为何会出现该警告以及当前写法是否正确。
原缓存函数代码
Public Shared Async Function downloadStringAndCacheAsync(fileName As String, MaxtimeElapsedInSeconds As Long, GetResultFromSomeOperation As Func(Of Task(Of String))) As Task(Of String) Dim fileDate = IO.File.GetLastWriteTime(fileName) Dim timeElapsedInSeconds = (Now - fileDate).TotalSeconds Dim cachedVersion = "" If timeElapsedInSeconds > MaxtimeElapsedInSeconds Then Dim resultTask = GetResultFromSomeOperation() ' so function1() return Task(Of String) Dim result = Await resultTask TexttoFile(result, fileName, False) cachedVersion = result Else cachedVersion = fileToText(fileName) End If Return cachedVersion End Function
调用代码及警告信息
调用代码
Dim str1 = Await CookieAwareWebClient.downloadStringAndCacheAsync _ ("First5000Coins", 3600, Function() CookieAwareWebClient.downloadString1Async(url, "", {"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}) End Function)
警告内容
Severity Code Description Project File Line Suppression State Warning BC42358 Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call. nicehash2
警告原因
问题出在你传入的多行Lambda表达式上:VB.NET中,多行Lambda如果没有显式的Return语句,编译器会默认把它当作无返回值的Sub,而不是你需要的Func(Of Task(Of String))。此时downloadString1Async返回的Task(Of String)被直接丢弃,编译器检测到这个未被处理的异步任务,就触发了BC42358警告。
你的核心理解是对的:不需要在Lambda里await downloadString1Async,它只需返回Task(Of String)由downloadStringAndCacheAsync内部await即可,只是Lambda的写法有误。
修正方法
方法1:多行Lambda添加显式Return
在多行Lambda中明确返回downloadString1Async的结果:
Dim str1 = Await CookieAwareWebClient.downloadStringAndCacheAsync _ ("First5000Coins", 3600, Function() Return CookieAwareWebClient.downloadString1Async(url, "", {"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}) End Function)
方法2:简化为单行Lambda
单行Lambda不需要显式Return,编译器会自动返回表达式结果:
Dim str1 = Await CookieAwareWebClient.downloadStringAndCacheAsync _ ("First5000Coins", 3600, Function() CookieAwareWebClient.downloadString1Async(url, "", {"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}))
原函数的正确性
你编写的downloadStringAndCacheAsync函数逻辑完全正确:仅当缓存过期时才调用传入的异步操作获取数据并缓存到本地,否则直接读取本地缓存。内部对GetResultFromSomeOperation()返回的Task执行await的处理方式是合理的。
内容的提问来源于stack exchange,提问作者user4951
相关产品推荐
相关产品推荐

