具有异步的多个请求并等待消耗更多时间然后循环

时间:2017-06-04 04:38:50

标签: c# asynchronous async-await task

我上传的文件包含一个数字列表,并为文件中的每个号码发送一个请求。我尝试用for循环发送一次请求,用async和await发送一次,令我惊讶的是循环更快。以下是代码。

public async Task<ActionResult> IndexWithThread() {

        messageStatus = new MessageStatus();
        if (Request.Files["msisdnlist"] != null)
        {
            Task st1;
            List<Task> task = new List<Task>();
            StreamReader file = new StreamReader("C:\\Users\\SUMAN\\Desktop\\msisdn.txt");
            while ((line = file.ReadLine()) != null)
            {
                string url = "api/sendmessage/" + line;
                st1 = ProcessRequest(url, client);
                task.Add(st1);

            }
            await Task.WhenAll(task.ToArray());
            watch.Stop();
            file.Close();

        }
        return View("Index", messageStatus);
    }

    private async Task ProcessRequest(string url,HttpClient client) {

        var response = await client.GetAsync(url);
        int status = GetStatusCode(response.StatusCode.ToString());
        if (status == 200)
            success++;
        else
            failed++;
        count++;

        timeTaken = watch.Elapsed.ToString();

    } 

这是请求方法。

  public HttpResponseMessage Get(int id)
    {
        Thread.Sleep(5000);
        int randomNum =GetRandomResponse();
        if(randomNum==1)
            return Request.CreateResponse(HttpStatusCode.OK, "Succeessfully send message to msisdn "+id);
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error sending message to msisdn "+id);
    }

我哪里出错了?在这种情况下,处理多个请求的最佳选择是什么?

修改

for循环代码

     public ActionResult Index()
      {
        var watch = Stopwatch.StartNew();
        string line;
        int success=0;
        int failed = 0;
        int count =0;
        MessageStatus messageStatus = new MessageStatus();

        if (Request.Files["msisdnlist"] != null)
        {
            StreamReader file = new StreamReader("C:\\Users\\ADMIN\\Desktop\\msisdn.txt");
            while ((line = file.ReadLine()) != null)
            {
                string url = "api/sendmessage/"+line;
                var response = client.GetAsync(url).Result;
                //Response.StatusCode = GetStatusCode(response.StatusCode.ToString());
                int status = GetStatusCode(response.StatusCode.ToString());
                if (status == 200)
                    success++;
                else
                    failed++;
                count++;
            }
            watch.Stop();
            string timeTaken = watch.Elapsed.ToString();
            file.Close();

            messageStatus.Success = success;
            messageStatus.Failed = failed;
            messageStatus.TimeTaken = timeTaken;
            messageStatus.MsisdnCount = count;

        }
        return View(messageStatus);

    }

我添加了thread.sleep()来延迟请求。两种方法之间的时差差别不大,异步需要几秒钟。

1 个答案:

答案 0 :(得分:-3)

修改你的get方法,因为它在同一个代码块中包含两个return语句。

   public HttpResponseMessage Get(int id)
    {
        Thread.Sleep(5000);
        int randomNum =GetRandomResponse();
        if(randomNum==1)
{
            return Request.CreateResponse(HttpStatusCode.OK, "Succeessfully send message to msisdn "+id);
}
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error sending message to msisdn "+id);
    }