问题
我有一个C#应用程序,其中有大约40至50个不同的Asana Task ID。我想要每个ID的详细信息,所以我要做的是在for循环中为每个ID发出请求。数据为JSON格式:
// For each result in the data.
foreach (var result in results["data"])
{
// ID for each Asana task in the data.
string id = (string)result["id"];
// Deserialize the JSON data so we can use it with an object and its properties.
deserialize.SetJsonData(requestAsana.getSingleAsanaTask(id));
// Add data to the list.
asanaDataList.Add(deserialize.Data);
}
SetJsonData
方法反序列化JSON数据:
private AsanaRootData root = new AsanaRootData();
public string jsonData;
public string SetJsonData(string json)
{
this.jsonData = json;
root = JsonConvert.DeserializeObject<AsanaRootData>(jsonData);
return json;
}
getSingleAsanaTask
方法是使用给定ID向Asana发送请求的方法:
public string getSingleAsanaTask(string taskID)
{
try
{
// Make a request variable with URL and ID.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(taskURL + taskID);
// Speed up requests.
request.Proxy = null;
// Encode authentication value.
String encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(auth));
// Add authentication to header.
request.Headers.Add("Authorization", "Basic " + encoded);
// Response variable.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
return readStream.ReadToEnd();
}
catch (WebException e)
{
Debug.WriteLine("\nInvalid Asana task ID\n");
}
return "";
}
问题
有时我要加载50多个任务,但可能最多需要20秒。有没有办法提高性能,或者我做错了吗?
HTTPWebRequest
变量,这有关系吗?我尝试了什么?
ServicePointManager.DefaultConnectionLimit = connectionLimit;
req.Proxy = null;
ServicePointManager.Expect100Continue = false;
用于setJsonData
方法的线程。
Stopwatch timer = new Stopwatch();
,其中请求花费了大约40%的时间。
缩小到
HttpWebResponse response = (HttpWebResponse)request.GetResponse();