gpt4 book ai didi

c# - System.Threading.Tasks 中的 NullReferenceException 调用 HttpClient.GetAsync(url)

转载 作者:可可西里 更新时间:2023-11-01 08:17:01 25 4
gpt4 key购买 nike

我的 MVC 4.0 应用程序有一个奇怪的问题。我使用 REST 网络服务 (Amazon Associate)。我创建了一种方法,可以在任何地方使用。缩短版是这样的:

    private async Task<XElement> GetRequest(string url)
{
string myresponse;
HttpResponseMessage response = null;
HttpClient client = new HttpClient();
try
{
response = await client.GetAsync(url);
myresponse = response.Content.ToString();
if (myresponse.Contains("503"))
{
myTrace.WriteLine("503 Sleep.....");
Thread.Sleep(3000); // looks like amazon us does not like fast requests....
return await GetRequest(url); //restart after pausing....
}
}
catch (TaskCanceledException ex)
{
myTrace.WriteLine("TaskCancelled From GetRequest: " + ex);
return null;
}

catch (HttpRequestException ex)
{
myTrace.WriteLine("RequestException Sleep.....");
Thread.Sleep(300000); // 5 minutes de pause
}

catch (Exception ex)
{
myTrace.WriteLine("From GetRequest: " + ex);
return null;
}

try
{
XElement content = await response.Content.ReadAsAsync<XElement>();
response.Dispose();
client.Dispose();
return content;
}
catch (Exception)
{
return null;
}
}

没什么特别的,它确实工作得很好......但是,现在,在一个特定的调用中,它会在 client.GetAsync(url) 上爆炸。起初我怀疑 url 中的某些内容是错误的,所以我从调试器 session 中抓取它并将其直接粘贴到我的浏览器中,得到了预期的答案...

所以,URL 没有问题。做了一点单元测试,使用相同的特定 URL 工作得很好......

当它在调试器中爆炸时,很难看出哪里出了问题。 (没有抛出异常!)。最后,我通过 IntelliTrace 看到存在异常,似乎在 System.Threading.Tasks 中。很难确定,因为调用堆栈对我的非专家眼来说有点困惑....

这是我从之前的代码中获得的调用堆栈:

>   System.Web.dll!System.Web.ThreadContext.AssociateWithCurrentThread(bool setImpersonationContext = {unknown})    C#
System.Web.dll!System.Web.HttpApplication.OnThreadEnterPrivate(bool setImpersonationContext = {unknown}) C#
System.Web.dll!System.Web.HttpApplication.OnThreadEnter() C#
System.Web.dll!System.Web.HttpApplication.System.Web.Util.ISyncContext.Enter() C#
System.Web.dll!System.Web.Util.SynchronizationHelper.SafeWrapCallback(System.Action action = {unknown}) C#
System.Web.dll!<>c__DisplayClass9.AnonymousMethod(System.Threading.Tasks.Task _ = {unknown}) C#
mscorlib.dll!System.Threading.Tasks.ContinuationTaskFromTask.InnerInvoke() C#
mscorlib.dll!System.Threading.Tasks.Task.Execute() C#
mscorlib.dll!System.Threading.Tasks.Task.ExecutionContextCallback(object obj = {unknown}) C#
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext = {unknown}, System.Threading.ContextCallback callback = {unknown}, object state = {unknown}, bool preserveSyncCtx = {unknown}) C#
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext = {unknown}, System.Threading.ContextCallback callback = {unknown}, object state = {unknown}, bool preserveSyncCtx = {unknown}) C#
mscorlib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref System.Threading.Tasks.Task currentTaskSlot = {unknown}) C#
mscorlib.dll!System.Threading.Tasks.Task.ExecuteEntry(bool bPreventDoubleExecution = {unknown}) C#
mscorlib.dll!System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() C#
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() C#
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() C#

无论如何,这看起来肯定与 Tasks、Async、Background worker 等相关...是否有“清除”所有其他正在运行的任务以避免此问题的好方法?

感谢您的帮助,伯纳德。

最佳答案

除了@kcar 的回答之外,我遇到了一个非常相似的问题,即代码路径上有多个等待,其中有一个未等待的方法,例如:

public async Task JsonResult BookThing(InputModel model)
{
// Do some stuff
thisIsAnAsyncMethod(Model model); // Fire and forget
return Json(null);
}

protected async Task thisIsAnAsyncMethod(Model model)
{
await oneThing();
await anotherThing();
await somethingElse();
}

这导致等待随机失败而没有让我捕获异常 - 因为 TPL 试图重新加入一个已被取消的上下文,所以它在 try/catch 之外抛出 NullReferenceException。

这很难诊断。在生产环境中,您不会在 try/catch 中看到任何内容,而在 Visual Studio 中,等待重新加入原始上下文的计划有点随机——这取决于 TaskScheduler 碰巧决定做什么。

如果您不想触发并忘记,显而易见的答案是等待异步方法 - 您将收到编译器警告,提醒您这样做。

如果您确实想触发并忘记解决方案是显式启动一个新任务。最好的方法是 covered in this answer about fire and forget Tasks .

关于c# - System.Threading.Tasks 中的 NullReferenceException 调用 HttpClient.GetAsync(url),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16056016/

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