user12041324
user12041324

Reputation:

How to async httpwebrequest and thread

I am trying to async httpwebrequest for 3 days i trying every thing First My code is

HttpWebRequest httpWebRequest0_1 = (HttpWebRequest)WebRequest.Create("dir.com" + "/access_token.json");
httpWebRequest0_1.AllowAutoRedirect = true;
httpWebRequest0_1.KeepAlive = true;
httpWebRequest0_1.UseDefaultCredentials = true;
httpWebRequest0_1.Headers.Add(this.string_6, string_5);

I want to send async request each time but my CPU and RAM usage 100% And my async Method is

Enumerable.Range(0, 5).ToList().ForEach(f =>
{
    new Thread(() =>
    {   
        method_6();
        Thread.sleep(1000);
    }).Start();
});

I want to send request for 1 sec each time.

Upvotes: 0

Views: 90

Answers (1)

Fildor
Fildor

Reputation: 16104

With the limited snippet in question, I'd suggest using TAP as follows:

async Task RequestAsync()
{
    for ( int i = 0; i < 5; i++ )
    {
        await method_6();
        await Task.Delay(TimeSpan.FromSeconds(1));
    }
}

Assuming method_6 is doing the webrequest, it would have to be changed:

async Task method_6()
{
     // Create WebRequest httpWebRequest0_1  like in question

     await httpWebRequest0_1.GetResponseAsync();
}

Upvotes: 1

Related Questions