Diab
Diab

Reputation: 124

C# Code keeps repeating

I am trying to execute a code through a loop like this

for(int i = 0; i < x; i++)
{
await Post(i,1,2,3);
MessageBox.Show("Success");
}

and the post method basically posts data to a certain website

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Website");
request.Method = WebRequestMethods.Http.Post;
request.KeepAlive = true;
request.CookieContainer = cookie;
string datatowrite = i + "Some data"+ 2 + 3 + 4 + 5 //as string ofc
byte[] data = Encoding.UTF8.GetBytes(datatowrite);
request.ContentLength = data.Length;
using (Stream stream = await request.GetRequestStreamAsync())
{
    await stream.WriteAsync(data, 0, data.Length);
}

The loop executes well the first 2 times the third time it doesn't (It reaches the line with the Post() method then doesn't do anything doesn't even execute the message.

so I tried to place some breakpoints in the Post() method and found that it keeps repeating it self multiple times (without any loops) and weirdly enough finally executes after and only after using the breakpoints .

PS. the methods works fine if I did it without looping like

Post(1,2,3,4);
Post(2,2,3,4);
Post(3,2,3,4);

etc But I need to use the loop since x is entered by the user

Thanks

Upvotes: 1

Views: 303

Answers (1)

Diab
Diab

Reputation: 124

Solved

I wasn't closing the httpwebrequest after completeion using abort() method thanks to Marko

Upvotes: 1

Related Questions