HttpWebRequest.GetResponseAsync如何因OutOfMemoryException而失败?

时间:2015-04-11 12:33:19

标签: c# windows-runtime httpwebrequest winrt-async

我正在编写处理来自Web服务的数据的代码。 HTTP请求本身采用async方法,看起来非常像这样:

private async Task<IEnumerable<string[]>> GenericGrab(string query)
{
    var req = WebRequest.Create(new Uri("http://example.org/" + query)) as HttpWebRequest;
    HttpWebResponse res;
    try
    {
        res = (HttpWebResponse) await req.GetResponseAsync(); // BOOM!
    }
    // Boring exception handlers skipped
    StreamReader read = new StreamReader(res.GetResponseStream());
    string l;
    while (true) {
        l = await read.ReadLineAsync().ConfigureAwait(false);
        if (l == null) break;
        // Process lines here
    }
    // Return result of processing
}

此方法用于针对Web服务的各种不同请求。它大部分时间都可以工作,但是当有更多数据时(似乎所有响应都低于1 MB),它似乎都会失败。如果失败,代码中标记为 BOOM!GetResponseAsync调用会在OutOfMemoryException中生成mscorlib.ni.dll。不出所料,调用堆栈并不是非常有用的信息:

myapp.exe!MyApp.App.InitializeComponent.AnonymousMethod__1e(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e) Line 50  C#
    [Native to Managed Transition]  
    [Managed to Native Transition]  
    mscorlib.ni.dll!System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RoReportUnhandledError(System.Runtime.InteropServices.WindowsRuntime.IRestrictedErrorInfo error)    Unknown
    mscorlib.ni.dll!System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.ReportUnhandledError(System.Exception e)    Unknown
    System.Runtime.WindowsRuntime.NI.DLL!System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()  Unknown
    System.Runtime.WindowsRuntime.NI.DLL!System.Threading.WinRTSynchronizationContext.Invoker.InvokeInContext(object thisObj)   Unknown
    mscorlib.ni.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)    Unknown
    mscorlib.ni.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)    Unknown
    System.Runtime.WindowsRuntime.NI.DLL!System.Threading.WinRTSynchronizationContext.Invoker.Invoke()  Unknown

(调试器在VS生成的App.g.i.cs中断;代码似乎是异常的通用捕获器。)

我不明白这里会发生什么......我理解API的方式,响应的大小应该无关紧要,因为它正在作为流处理(使用GetResponseStream) ,无论如何都会抛出异常。

任何人都可以向我解释可能导致这种情况的原因吗?

1 个答案:

答案 0 :(得分:0)

尝试处理“res”变量,并告诉我它是否更好。我过去有几个问题,因为我忘了在HttpWebResponse对象上做这个。

相关问题