问题仅发生在我的客户端计算机上。我在 4 台机器上运行我的应用程序,但没有成功复制。
在使用 Flurl 库时,我想就调试以下异常提出建议和帮助:
什么可能导致此异常仅在特定机器上运行?
System.TypeInitializationException:“Module.Performance.PriceProviders.YahooClientFactory”的类型初始化程序引发了异常。---> System.AggregateException:发生一个或多个错误。---> System.NullReferenceException:对象引用未设置为对象的实例。在 Flurl.Http.FlurlClient.ReadResponseCookies(HttpResponseMessage response) 在 Flurl.Http.FlurlClient.d__28.MoveNext()
--- 内部异常堆栈跟踪结束 --- 在 System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)在 System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task
1.get_Result() 在 Module.Performance.PriceProviders.YahooClientFactory..cctor() --- 内部异常堆栈跟踪结束 --- 在 Module.Performance.PriceProviders.YahooClientFactory.get_GetYahooClient() 在 Module.Performance.PriceProviders.YahooFlurlClient .d__9.MoveNext() --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task ) 在 Module.Performance.PriceProviders.YahooStockPriceProvider.d__0.MoveNext() --- 从先前抛出异常的位置结束堆栈跟踪--- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime .CompilerServices.TaskAwaiter。Module.Performance.PriceProviders.PriceProviderBase.d__3.MoveNext() 处的 HandleNonSuccessAndDebuggerNotification(任务任务)
异常下方的代码如下所示:
YahooClientFactory 是优化请求时间的单调因素。工厂经常被其他异步任务(更高层)调用
public static class YahooClientFactory
{
public static IFlurlClient GetYahooClient => YahooClientInstance;
public static string Crumb { get; }
private static readonly IFlurlClient YahooClientInstance;
private const string CookieUrl = "https://finance.yahoo.com";
private static string userAgent = "User-Agent";
private static string headerString =
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36";
private const string CrumbUrl = "https://query1.finance.yahoo.com/v1/test/getcrumb";
private static int MaxRetryCount = 5;
static YahooClientFactory()
{
YahooClientInstance = new FlurlClient()
.WithHeader(userAgent, headerString)
.EnableCookies()
.WithUrl($"{CookieUrl}?{GetRandomString(8)}");
for (int i = 0; i < MaxRetryCount; i++)
{
YahooClientInstance
.GetAsync(CancellationToken.None)
.Result
.EnsureSuccessStatusCode();
if (YahooClientInstance.Cookies?.Count > 0)
{
break;
}
if (i == MaxRetryCount)
{
throw new Exception("Reached maximum number of retries when connecting to yahoo client.");
}
Thread.Sleep(100);
}
Crumb = YahooClientInstance
.WithUrl(CrumbUrl)
.GetAsync(CancellationToken.None)
.ReceiveString()
.Result;
}
public static string GetRandomString(int length)
{
const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
return string.Join("", Enumerable.Range(0, length).Select(i => Chars[new Random().Next(Chars.Length)]));
}
}