gpt4 book ai didi

c# - 中止 GetResponseAsync() 和任务中的异常

转载 作者:行者123 更新时间:2023-11-30 15:30:00 25 4
gpt4 key购买 nike

我写了一个方法,它从 eq 中获取 ETag。服务器上的 XML 文件。如果超时(GetResponseAsync() 没有CancellationToken),我是否正确编写了中止任务并且我不知道如何执行Exception

代码如下:

    public static async Task<string> GetETagAsync(Uri feedLink)
{
const int millisecondsTimeout = 2500;
WebRequest webRequest = WebRequest.Create(feedLink);
webRequest.Method = "HEAD";
try
{
Task<WebResponse> webResponse = webRequest.GetResponseAsync();
if (await Task.WhenAny(webResponse, Task.Delay(millisecondsTimeout)) == webResponse)
{
using (var result = webResponse.Result)
{
return result.Headers["ETag"];
}
}
else
{
webRequest.Abort();
return null;
}
}
catch (Exception)
{
return null;
}
}

编辑

我做了一些改变。重写异常并使用本主题中的类:GetResponseAsync does not accept cancellationToken

代码:

    public static async Task<string> GetETagAsync(Uri feedLink)
{
const int millisecondsTimeout = 2500;
var cancellationTokenSource = new CancellationTokenSource();
WebRequest webRequest = WebRequest.Create(feedLink);
webRequest.Method = "HEAD";

try
{
Task<WebResponse> webResponse = WebRequestExtensions.GetResponseAsync(webRequest, cancellationTokenSource.Token);
if (await Task.WhenAny(webResponse, Task.Delay(millisecondsTimeout)) == webResponse)
{
using (var result = webResponse.Result)
{
return result.Headers["ETag"];
}
}
else
{
cancellationTokenSource.Cancel();
return null;
}
}
catch (AggregateException ex)
{
if (ex.InnerException is WebException)
return null;

throw;
}
}

public static class WebRequestExtensions
{
public static async Task<WebResponse> GetResponseAsync(this WebRequest request, CancellationToken cancellationToken)
{
using (cancellationToken.Register(() => request.Abort(), useSynchronizationContext: false))
{
try
{
var response = await request.GetResponseAsync();
cancellationToken.ThrowIfCancellationRequested();
return (WebResponse)response;
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.RequestCanceled)
{
cancellationToken.ThrowIfCancellationRequested();
}

if (cancellationToken.IsCancellationRequested)
{
throw new TaskCanceledException(ex.Message, ex);
}

throw;
}
}
}
}

现在正确吗?

最佳答案

您可以使用我在此处编写的WebRequestExtensions 类来解决问题: https://github.com/openstacknetsdk/openstack.net/blob/master/src/corelib/Core/WebRequestExtensions.cs

此类完全支持 CancellationTokenWebRequest.Timeout 属性。

关于c# - 中止 GetResponseAsync() 和任务中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22796061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com