2 years ago

#59539

test-img

mohammad noori

C# - Multiple web request at the same time

I want to fetch some data from a web api at same time. so I wrote this code :

public string GetData(string x)
{
    try
    {
        string URL = "https://MyApi.com/api?data=" + x;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());

        dynamic stuff = JsonConvert.DeserializeObject(reader.ReadToEnd());

        string res = stuff.Data;

        return res;

     }
     catch (Exception ee)
     {
         throw ee;
     }
}

And in my main method I wrote this :

try
{
    var tasks = new Task<string>[60];

    for (int i = 0; i < 59; i++)
        tasks[i] = Task.Factory.StartNew(() => GetData("item" + i.ToString()));

    Task.WaitAll(tasks);

    List<string> Results = new List<string>();

    for (int i = 0; i < tasks.Count(); i++)
        Results.Add(tasks[i].Result);
}
catch (Exception ee)
{
}

So the problem is when I call GetData() method Directly (Once), I get my data in less than 1 second. But when I want to simulate to get 60 data at same time using multithreading , it takes more than 7 to 8 seconds. But I want this process takes less than 1 seconds and happen at same time. And server has no limitation for requesting at same time. (I implemented this code in Android and I had no problem.)

c#

multithreading

httpwebrequest

0 Answers

Your Answer

Accepted video resources