我正在尝试使用异步来执行文件的解压缩。目前我收到警告“异步方法缺少'等待'操作符因此将同步运行。”
当我尝试调用ExtractAll函数时,例如:
Await zip1.ExtractAll(sFolderExtracted, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently)
我收到编译错误“Expression does not produce a value
”
Public Shared Async Function UnzipFile(sTempFolder As String, sZipFile As String, sRecordID As String) As Task(Of ExtractedFiles)
Dim oExtractedFiles As New ExtractedFiles
Dim TargetFile As String = sZipFile
Dim sFolderExtracted As String = Path.Combine(sTempFolder, sRecordID) ' i.e. TEMP\12345
Try
Using zip1 As Ionic.Zip.ZipFile = Ionic.Zip.ZipFile.Read(TargetFile)
zip1.ExtractAll(sFolderExtracted, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently)
'Populate ExtractedFiles class object with data about the extraction
oExtractedFiles.sImageFront = GetImageBySide(sFolderExtracted, Cheque.ImageSide.Front)
oExtractedFiles.sImageRear = GetImageBySide(sFolderExtracted, Cheque.ImageSide.Rear)
oExtractedFiles.iRecordID = CInt(sRecordID)
Return oExtractedFiles
End Using
Catch ex As Exception
msgbox(ex.toString)
End Try
End Function
如何使用异步运行上述代码?有什么想法吗?
答案 0 :(得分:1)
我不熟悉您用于压缩的库,但看起来zip1.ExtractAll
不是您可以等待的async
方法。
听起来你想将冗长的zip解压缩操作卸载到另一个线程上,等待它。您可以通过将要运行的代码包装在Task.Run的调用内的其他线程上来实现。
尝试这样的事情:
Public Shared Async Function UnzipFile(sTempFolder As String, sZipFile As String, sRecordID As String) As Task(Of ExtractedFiles)
Dim TargetFile As String = sZipFile
Dim sFolderExtracted As String = Path.Combine(sTempFolder, sRecordID) ' i.e. TEMP\12345
Try
Using zip1 As Ionic.Zip.ZipFile = Ionic.Zip.ZipFile.Read(TargetFile)
Return Await Task.Run(Function()
zip1.ExtractAll(sFolderExtracted, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently)
'Populate ExtractedFiles class object with data about the extraction
Dim oExtractedFiles As New ExtractedFiles
oExtractedFiles.sImageFront = GetImageBySide(sFolderExtracted, Cheque.ImageSide.Front)
oExtractedFiles.sImageRear = GetImageBySide(sFolderExtracted, Cheque.ImageSide.Rear)
oExtractedFiles.iRecordID = CInt(sRecordID)
Return oExtractedFiles
End Function)
End Using
Catch ex As Exception
msgbox(ex.toString)
End Try
End Function
此外,考虑重命名您的功能,使其明显是一个等待功能。像UnzipFileTaskAsync
之类的东西,或类似的东西。
答案 1 :(得分:0)
我正在尝试使用异步来执行文件的解压缩。目前我收到了警告"异步方法缺乏等待'等待'运营商将同步运行。"
您无法使用async
/ await
来强制某些内容异步"。有些东西要么是异步的,要么不是。我不知道Ionic.Zip是否有一个您可以使用await
自然消耗的异步API。
但是(假设这是一个UI应用程序),您可以通过在线程池线程上运行(同步)来假装异步。这里的正确工具称为Task.Run
。
首先,让您的同步方法具有同步API:
Public Shared Function UnzipFile(sTempFolder As String, sZipFile As String, sRecordID As String) As ExtractedFiles
然后您可以使用Task.Run
:
Await Task.Run(Function () zip1.ExtractAll(sFolderExtracted, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently))