我在使用ContinueWith lambda子函数编写这个DecompressionHandler时遇到了麻烦。我收到的错误是“'Async'修饰符只能用于Subs,或者用于返回Task或Task(Of T)的函数。”在ContinueWith子函数内。我不知道问题是什么或如何解决它。
Public Class DecompressionHandler
Inherits DelegatingHandler
Public Compressors As List(Of ICompressor)
Public Sub New()
Compressors = New List(Of ICompressor)()
Compressors.Add(New GZipCompressor())
Compressors.Add(New DeflateCompressor())
End Sub
Protected Overrides Async Function SendAsync(request As HttpRequestMessage, cancellationToken As CancellationToken) As Task(Of HttpResponseMessage)
Return Await MyBase.SendAsync(request, cancellationToken).ContinueWith(Of HttpResponseMessage)(Async Function(responseToCompleteTask)
Dim response As HttpResponseMessage = responseToCompleteTask.Result
If response.Content.Headers.ContentEncoding IsNot Nothing AndAlso response.Content IsNot Nothing Then
Dim encoding = response.Content.Headers.ContentEncoding.First()
Dim compressor = Compressors.FirstOrDefault(Function(c) c.EncodingType.Equals(encoding, StringComparison.InvariantCultureIgnoreCase))
If compressor IsNot Nothing Then response.Content = Await DecompressedContentAsync(response.Content, compressor).ConfigureAwait(False)
End If
Return response
End Function)
End Function
Private Shared Async Function DecompressedContentAsync(compressContent As HttpContent, compressor As ICompressor) As Task(Of StreamContent)
Using compressContent
Dim decompressed As New MemoryStream
Await compressor.Decompress(Await compressContent.ReadAsStreamAsync, decompressed)
Dim newContent As New StreamContent(decompressed)
newContent.Headers.ContentType = compressContent.Headers.ContentType
Return newContent
End Using
End Function
End Class
答案 0 :(得分:0)
Async Function(responseToCompleteTask)
因为它返回HttpResponseMessage
将其更改为:
Function(responseToCompleteTask)
答案 1 :(得分:0)
我解决了它...如果删除Async / Await函数并更改DecompressedContentAsync(response.content,compressed).Result()
那是有效的......戴夫是正确的一半...
答案 2 :(得分:0)
只需使用Await
代替ContinueWith
。我的VB生锈了,但这应该给你一个想法:
Protected Overrides Async Function SendAsync(request As HttpRequestMessage, cancellationToken As CancellationToken) As Task(Of HttpResponseMessage)
Dim response as HttpResponseMessage = Await MyBase.SendAsync(request, cancellationToken)
If response.Content.Headers.ContentEncoding IsNot Nothing AndAlso response.Content IsNot Nothing Then
Dim encoding = response.Content.Headers.ContentEncoding.First()
Dim compressor = Compressors.FirstOrDefault(Function(c) c.EncodingType.Equals(encoding, StringComparison.InvariantCultureIgnoreCase))
If compressor IsNot Nothing Then response.Content = Await DecompressedContentAsync(response.Content, compressor).ConfigureAwait(False)
End If
Return response
End Function