Question

I am trying to send the POST requests to the web server, they all have to be done at the same time.
I've made the code below, but it's sending the requests about 4 per second. For example, if I want to send 20 POST requests, it will take about 6 seconds, and they're not sent simultaneously as I want.
I have tried to set ServicePointManager.DefaultConnectionLimit and ServicePointManager.MaxServicePoints higher, but it's still the same.

class BrowserAsync
{
    private HttpWebRequest WebReq;

    public void makePOST(string url, string POST)
    {
        byte[] buffer = Encoding.ASCII.GetBytes(POST);
        WebReq = (HttpWebRequest)WebRequest.Create(url);

        WebReq.Headers.Clear();
        // CUSTOM HEADERS HERE -- not shown in this example

        WebReq.KeepAlive = false;
        WebReq.Proxy = null;

        WebReq.Method = "POST";
        WebReq.ContentType = "application/x-www-form-urlencoded";
        WebReq.ContentLength = buffer.Length;

        Stream PostData = WebReq.GetRequestStream();
        PostData.Write(buffer, 0, buffer.Length);
        PostData.Close();

        WebReq.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
    }

    private void FinishWebRequest(IAsyncResult result)
    {
        // data returned is not important, just end it
        WebReq.EndGetResponse(result);
    }
}



Every instance is getting called from it's own thread:

public static void waitAndExecute(object threadInfo)
{
    // this is the thread on it's own
    ThreadInformation info;
    info = (ThreadInformation)threadInfo;

    // WAIT
    // Display("Sleeping until " + DateTime.Now.AddMilliseconds((info.exTime - DateTime.Now).TotalMilliseconds - info.ping)
    // the same sleeping time is displayed for all threads
    System.Threading.Thread.Sleep((int)(info.exTime - DateTime.Now).TotalMilliseconds - info.ping);

    BrowserAsync brw = new BrowserAsync();
    brw.makePOST("url", info.postParameters);
}

No correct solution

OTHER TIPS

You could use HttpClient and PostAsync.

You can pass the second parameter HttpContent using the StringContent class e.g.

var client = new HttpClient();
client.PostAsync(url, new StringContent(POST));

See here https://stackoverflow.com/a/13155225/1202600 for an example of kicking all the requests off at the same time but with GetAsync

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top