我正在尝试通过C#查询数据来使用Microsoft Project OData。我遇到性能问题,每个查询的延迟时间约为1秒。我试图使用该方法一次查询2条信息:
public static async Task<string> ReadXml(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = Credentials; // SharePointOnlineCredentials
request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var stream = response.GetResponseStream())
using (var reader = new System.IO.StreamReader(stream))
{
var xml = await reader.ReadToEndAsync();
return xml;
}
}
如果我调用它并一直等待它结束再再次调用它,则效果很好,但是如果我多次调用它,我将永远不会收到来自WebRequest的任何响应:
// just an example. I usually put a condition to filter for the tasks of a single project
var query1 = ReadXml(@"https://something.sharepoint.com/sites/pwa/_api/ProjectData/Projects");
var query2 = ReadXml(@"https://something.sharepoint.com/sites/pwa/_api/ProjectData/Tasks");
Task.WaitAll(query1, query2);
如果我“等待”第一个,然后执行第二个,则可以正常工作,但不能使用上面的代码。并假设项目中有<300个任务,如果超出这个数量,我必须以300个块的形式查询它们,导致整个查询花费4或5秒钟,因为我无法一次完成所有任务! 有没有办法同时发送多个请求? 我可以通过简单地在多个chrome标签中输入url来做到这一点,而且响应速度更快。我不明白为什么它不适用于我的代码!
谢谢
答案 0 :(得分:1)
根据以下Webrequest.Create可能是问题,它使用内部阻塞方法C# Thread UI is getting blocked | Possible reason WebRequest.Create?。
下面的代码使用较新的HttpClient,因此不应出现此问题。
public static HttpClient _HttpClient { get; } = new HttpClient(new HttpClientHandler { Credentials=new NetworkCredential("","")});
public static async Task<string> ReadXml(string url)
{
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, url))
{
requestMessage.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
using (var response = await _HttpClient.SendAsync(requestMessage))
{
return await response.Content.ReadAsStringAsync();
}
}
}