Problem
I have a C# application where I have around 40 to 50 different Asana Task ID's. I want details for each ID so what I do is make a request in a for loop for each ID. The data is in JSON format:
// 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);
}
The SetJsonData
method deserializes the JSON data:
private AsanaRootData root = new AsanaRootData();
public string jsonData;
public string SetJsonData(string json)
{
this.jsonData = json;
root = JsonConvert.DeserializeObject<AsanaRootData>(jsonData);
return json;
}
And the getSingleAsanaTask
method is the method doing requests to Asana with given ID:
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 "";
}
Questions
Sometimes I can have more than 50 tasks I want to load, still it can take up to 20 seconds. Is there a way to increase performance, or am I perhaps doing it wrong?
- I can see that I am creating a new
HTTPWebRequest
variable for each request, does that matter? - Could it be my deserializing method that slows everything down?
What have I tried?
ServicePointManager.DefaultConnectionLimit = connectionLimit;
req.Proxy = null;
ServicePointManager.Expect100Continue = false;
Threading for the
setJsonData
method.Stopwatch timer = new Stopwatch();
where the requests took around 40% of the time.
Narrowed down to
- The following line is taking half of the time:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();