Parallel and http request

  • Thread starter Thread starter want 2 Learn
  • Start date Start date
W

want 2 Learn

Guest
i am trying to do http test with Parallel.ForEach.

List<Task<int>> TaskList = new List<Task<int>>();
string xml = GetXml();
List<string> xmlList = new List<string>();
for (int i = 0; i < 10000; ++i)
{
string tmpXml = string.Format(xml, Guid.NewGuid().ToString());
xmlList.Add(tmpXml);
Task<int> t = SendHttpRequest(tmpXml, i);
TaskList.Add(t);
}
int count = 0;
Parallel.ForEach(TaskList,new ParallelOptions { MaxDegreeOfParallelism = 4 }, t =>
{
if (t.Status != TaskStatus.RanToCompletion)
t.Start();
});
Task.WaitAll(TaskList.ToArray());
int iSuccess = 0, iFailue = 0;
foreach (Task<int> s in TaskList)
{
if (s.Result == 200)
{
Interlocked.Increment(ref iSuccess);



}
else
{
Interlocked.Increment(ref iFailue);

}
}
Console.WriteLine(iSuccess + ":" + iFailue);

code for http request :

private static async Task<int> SendHttpRequest(string xml, int counter)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1096/Response.ashx");
byte[] bytes;
bytes = System.Text.Encoding.UTF8.GetBytes(xml);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
Console.WriteLine(responseStr + ":" + counter);
}
return (int)response.StatusCode;
}




1.i got error "System.InvalidOperationException: 'Start may not be called on a task that has completed.'"

this is why I added the check of

if (t.Status != TaskStatus.RanToCompletion)
t.Start();

is this solution correct or should I change it?

2. how can I check how many max request were open at the same time?

Continue reading...
 
Back
Top