方法在2秒后调用

时间:2014-01-03 05:22:35

标签: c#

HttpResponseMessage response = client.PostAsJsonAsync(ConfigurationManager.AppSettings[Constants.BidApiBaseURL], objClientBidRequest).Result;

if (response.StatusCode.ToString() == "OK")
{
   // Send request after 2 second for bid result
   string bidContent = "<iframe src=maps.google.com?gps=....></iframe>";

   for (int i = 1; i <= 4; i++)
   {
      lstExpertBidResponse.Add(
                    new BidResponse(
                        objClientBidRequest.RequestId.ToString(),
                        bidContent,
                        i.ToString(),
                        "W" + i.ToString(),
                        GetFeedBackScore("W" + i.ToString()),
                        GetExpertID("W" + i.ToString())
                        ));
    }
}

上面的代码是在for loop中制作样本数据,但是我会从2秒后需要调用的某些服务中得到这个结果,但是一旦获得response它将只执行一次从不执行。

4 个答案:

答案 0 :(得分:3)

您可以使用Thread.Sleep(2000)

答案 1 :(得分:2)

您可以使用Timer Class

aTimer = new System.Timers.Timer(1000 * 60 * 2);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true; 

或 您可以使用Timer.Elapsed Event

// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);

// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;

答案 2 :(得分:1)

您应该在对服务的调用中使用await语句。这样你的程序就会等到服务响应:

var task = await client.PostAsJsonAsync(
           ConfigurationManager.AppSettings[Constants.BidApiBaseURL], 
           objClientBidRequest);

// wait for service to complete

HttpResponseMessage response = task.result;
if (response.StatusCode.ToString() == "OK")
  // etc etc

在这里查看异步编程:http://msdn.microsoft.com/en-us/library/hh191443.aspx

答案 3 :(得分:0)

使用Thread.sleep方法在2秒后调用next语句。

HttpResponseMessage response = client.PostAsJsonAsync(ConfigurationManager.AppSettings[Constants.BidApiBaseURL], objClientBidRequest).Result;

    if (response.StatusCode.ToString() == "OK")
    {
        // Send request after 2 second for bid result
        Thread.Sleep(2000);
        string bidContent = "<iframe src=maps.google.com?gps=....></iframe>";

        for (int i = 1; i <= 4; i++)
        {
            lstExpertBidResponse.Add(
                new BidResponse(
                    objClientBidRequest.RequestId.ToString(),
                    bidContent,
                    i.ToString(),
                    "W" + i.ToString(),
                    GetFeedBackScore("W" + i.ToString()),
                    GetExpertID("W" + i.ToString())
                    ));
        }
    }