Search code examples
c#asp.nethttpwebrequest

Send Multiple Posts At A Time


I am using a SQL Query to select data from my database and storing the returned results in a Dictionary<string, string> I then use a foreach loop and Server.UrlEncode to create a Querystring like such

foreach (var onetwo in privatedictionary) 
    dataToPost = onetwo.Key+"="+Server.UrlEncode(onetwo.Value)+"&";

then once the data has been compiled into dataToPost I use HttpWebRequest to send the data

HttpWebRequest wbrq = (HttpWebRequest)WebRequest.Create("www.sitetohit.com");
{
  using (StreamWriter sw = new StreamWriter(wbrq.GetRequestStream()))
  {
    sw.Write(dataToPost);
  }
}

What is a way using Visual Studio 2015 to send multiple Posts at once?


Solution

  • There are multiple ways, the best that I experienced are bellows:

    Parallel.ForEach(privatedictionary, (dataToPost) =>
            {
                HttpWebRequest wbrq = (HttpWebRequest)WebRequest.Create("www.sitetohit.com");
                {
                    using (StreamWriter sw = new StreamWriter(wbrq.GetRequestStream()))
                    {
                        sw.Write(dataToPost);
                    }
                }
            });
    

    Or:

    foreach (var dataToPost in privatedictionary)
            {
                Task.Run(async () =>
                {
                    Foo foo = new Foo();
                    await foo.BarAsync(dataToPost);
                });
            }
    
      //Asynchronous Handling
      public class Foo
    {
        public async Task BarAsync(string dataToPost)
        {
            HttpWebRequest wbrq = (HttpWebRequest)WebRequest.Create("www.sitetohit.com");
            {
                using (StreamWriter sw = new StreamWriter(wbrq.GetRequestStream()))
                {
                    await sw.WriteAsync(dataToPost);
                }
            }
        }
    }
    

    You can use this:

    Parallel.ForEach(privatedictionary, (onetwo) =>
            {
                var dataToPost = onetwo.Key + "=" + Server.UrlEncode(onetwo.Value) + "&";
                HttpWebRequest wbrq = (HttpWebRequest)WebRequest.Create("www.sitetohit.com");
                {
                    using (StreamWriter sw = new StreamWriter(wbrq.GetRequestStream()))
                    {
                        sw.Write(dataToPost);
                    }
                }
            });