我有以下代码:
public class HttpRequestsHandler
{
public static T HttpGetWithContent<T>(string requestUrl)
{
using (var handler = new WebRequestHandler())
{
handler.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
using (var httpClient = new HttpClient(handler)
{
BaseAddress = new Uri(requestUrl),
Timeout = Timeout.InfiniteTimeSpan
})
{
using (var response = httpClient.GetAsync(requestUrl).Result)
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Gone)
{
var errorMessage = $"HttpRequestTask: Request failed with status {response.StatusCode} for URL: {requestUrl}";
throw new HttpException(errorMessage, (int)response.StatusCode);
}
return response.Content.ReadAsAsync<T>().Result;
}
}
}
}
public static T HttpGetWithContentWrapper<T>(string requestUrl)
{
return HttpGetWithContent<T>(requestUrl);
}
}
现在我打电话的时候:
private void Button_Click(object sender, DoWorkEventArgs e)
{
var worker = new BackgroundWorker();
worker.DoWork += (sender, args) =>
{
var url = UrlProvider.BuildRequestUrl();
var date = HttpRequestsHandler.HttpGetWithContent<DateTime>(url);
//More code...
};
worker.RunWorkerCompleted += (sender, args) =>
{
//more code...
};
worker.RunWorkerAsync();
}
它就像一个魅力,但当我用一个包装器方法:
private void Button_Click(object sender, DoWorkEventArgs e)
{
var worker = new BackgroundWorker();
worker.DoWork += (sender, args) =>
{
var url = UrlProvider.BuildRequestUrl();
var date = HttpRequestsHandler.HttpGetWithContentWrapper<DateTime>(url); //fails here
//More code...
};
worker.RunWorkerCompleted += (sender, args) =>
{
//more code...
};
worker.RunWorkerAsync();
}
以错误结束&#34;不可访问的区域&#34;。
现在我想这与我的一次性模式有关;我不熟悉。根据我的理解,它用于应用程序中的非托管资源,因此对象只存在于使用&#39;。
我不明白的是它如何在fisrt部分返回一个值而不是在第二个部分...
感谢,
更新 - 我很抱歉,从操作代码到使其工作我粘贴错了,我将其更改为原始代码给了我麻烦,谢谢
答案 0 :(得分:2)
尝试更改
public static T HttpGetWithContentWrapper<T>(string requestUrl)
{
return HttpGetWithContent<T>(string requestUrl);
}
到
public static T HttpGetWithContentWrapper<T>(string requestUrl)
{
return HttpGetWithContent<T>(requestUrl);
}
通过编写string requestUrl
作为参数,您实际上是将空字符串传递给您的方法。也许这就是导致错误的原因(假设您的实际代码中存在此错误,而不仅仅是在示例中)。