0
在我們的Xamarin Forms App中,我們必須從多個API中加載很多數據。 最簡單的方法是直接從PCL使用HttpClient,但是當有幾百個這樣的錯誤時,我得到了這個錯誤。爲什麼在創建System.Net.Http.HttpClient()的實例時收到NullReferenceException?
通過本頁,我可以在新的PCL項目中重現此問題。
using System;
using Xamarin.Forms;
namespace HTTPTest
{
public class HTTPTestPage : ContentPage
{
int Index = 0;
public HTTPTestPage()
{
Content = new Label
{
Text = "HTTP Test"
};
}
protected override void OnAppearing()
{
base.OnAppearing();
StartLoading();
}
void StartLoading()
{
for (int i = 0; i < 400; i++)
{
if (string.IsNullOrEmpty(LoadStringFromEndpoint("https://google.de")))
{
break;
}
}
}
public string LoadStringFromEndpoint(string url)
{
System.Diagnostics.Debug.WriteLine("LoadFromEndpoint: " + url);
try
{
Index++;
var client = new System.Net.Http.HttpClient();
return client.GetStringAsync(url).Result;
}
catch (NullReferenceException ex)
{
System.Diagnostics.Debug.WriteLine($"{ex.Message} at Index: {Index}");
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
return string.Empty;
}
}
}
,這是結果:
LoadFromEndpoint: https://google.de
Object reference not set to an instance of an object at Index: 123
at System.Net.Http.RuntimeOptions.Read() [0x0002c] in /Users/builder/data/lanes/3985/9d6e1ab1/source/xamarin-macios/src/ObjCRuntime/RuntimeOptions.cs:229
at System.Net.Http.RuntimeOptions.GetHttpMessageHandler() [0x00000] in /Users/builder/data/lanes/3985/9d6e1ab1/source/xamarin-macios/src/ObjCRuntime/RuntimeOptions.cs:265
at System.Net.Http.HttpClient.GetDefaultHandler() [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.4.0.121/src/mono/mcs/class/System.Net.Http/HttpClientEx.cs:36
at System.Net.Http.HttpClient..ctor() [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.4.0.121/src/mono/mcs/class/System.Net.Http/HttpClientEx.cs:24
at HTTPTest.HTTPTestPage.LoadStringFromEndpoint (System.String url) [0x00020] in [...]HTTPTest/HTTPTestPCL/HTTPTestPage.xaml.cs:41
如果我得到這個例外一次,之後加載文件,我也將獲得System.IO.Exception(太多打開的文件)。 有沒有辦法解決這個問題(最好不要使用它)?