2014-11-02 27 views
0

我正在构建表单应用程序并按下一个正在while循环中循环的按钮,直到它找到一些结果。但是这个循环正在请求某个服务器。我想在1分钟内将这些请求加入到最多5个请求中。所以需要有一些睡眠直到新的分钟开始的逻辑。请有人可以帮我吗?如何在赢得表单应用程序中每分钟处理5个请求

这里是我的代码:

 public int RPMCounter { get; set; } 

     private async void SearchCheapestAuction() 
     { 
      bool foundItem = false; 

      textBoxLogging.Clear(); 
      textBoxLogging.Text += System.Environment.NewLine + "start"; 

      // 1 stay loooping till you found this item for the buynowprice 
      while (!foundItem) 
      { 
       // 2 check if this is request number 5 in one minute 
       if (RPMCounter <= 5) 
       { 
        // 3 increase counter 
        RPMCounter++; 

        // 4 set searchparameters 
        var searchParametersPlayers = new PlayerSearchParameters 
        { 
         MaxBid = (uint)Convert.ToInt16(textBoxMaxStartPrice.Text), 
         MinBid = (uint)Convert.ToInt16(textBoxMinStartPrice.Text), 
         MaxBuy = (uint)Convert.ToInt16(textBoxMaxBuyNow.Text), 
         MinBuy = (uint)Convert.ToInt16(textBoxMinBuyNow.Text) 
        }; 

        // 5 run search query 
        var searchResponse = await client.SearchAsync(searchParametersPlayers); 

        // 8 check if the search found any results 
        if (searchResponse.AuctionInfo.Count > 0) 
        { 

         // 9 buy this player for the buy now price 
         var auctionResponse = await client.PlaceBidAsync(searchResponse.AuctionInfo.First(), searchResponse.AuctionInfo.First().BuyNowPrice); 

         // 10 stop searching/buying, I found my item for the right price 
         return; 
        } 
       } 
       else 
       { 
        // 11 I access the 5 rpm, sleep till the next minutes begin and go search again? 
        return; 
       } 
      } 

      textBoxLogging.Text += System.Environment.NewLine + "finished"; 
     } 
} 

回答

1

我不会这样处理。
您设计的方式将产生以下效果:您将在任意短的时间间隔内连续进行5次服务器请求,然后等待一分钟,然后以任意短的间隔连续再次调用5次。
如果这就是你打算做的,你能解释一下为什么你需要这种方式吗?
通过简单地让System.Timers.Timer间隔12秒并检查您的请求是否完成,可以轻松地将呼叫数量限制为每分钟5次。
如果是,并且您没有找到该项目,则可以制作一个新项目,如果不是,则可以等待下次定时器过期。

它可能是这个样子:

private Timer _requestTimer; 
private readonly object _requestLock = new object(); 
private bool _requestSuccessful; 

private void StartRequestTimer() 
{ 
    _requestTimer = new Timer(12 * 1000) { AutoReset = true }; 
    _requestTimer.Elapsed += requestTimer_Elapsed; 
    _requestTimer.Start(); 
} 

void requestTimer_Elapsed(object sender, ElapsedEventArgs e) 
{ 
    lock (_requestLock) 
    { 
     if (_requestSuccessful) 
     { 
      _requestTimer.Stop(); 
     } 
     else 
     { 
      TryNewRequest(); 
     } 
    } 
} 

private void TryNewRequest() 
{ 
    lock (_requestLock) 
    { 
     //try a new asynchronous request here and set _requestSuccessful to true if successful 
    } 
} 

在你的主要功能,你会先打电话TryNewRequest(),那么你会打电话StartRequestTimer()。请注意,该请求必须是异步的,才能正常工作。

+0

嗨马特,非常感谢您的回答。是的,这是我实现的目标:将呼叫数量限制为每分钟5次。你有代码的例子,请给我12秒间隔的定时器吗? – Ola 2014-11-03 09:58:07

+0

编辑了帖子并添加了一些代码。希望有帮助。 – 2014-11-03 11:17:27

相关问题