2012-12-18 2 views
4

foreach 문이 있는데 foreach 및 if 문 끝에서 호출되는 메서드가 마지막 실행 시간에서 3 초 후에 만 ​​실행되도록해야합니다. .마지막 사용 후 X 초 후에 메서드를 실행하십시오.

다음은 코드입니다.

//Go over Array for each id in allItems 
    foreach (int id in allItems) 
      { 
       if (offered > 0 && itemsAdded != (offered * 3) && tDown) 
       { 
        List<Inventory.Item> items = Trade.MyInventory.GetItemsByDefindex(id); 
        foreach (Inventory.Item item in items) 
        { 
         if (!Trade.myOfferedItems.ContainsValue(item.Id)) 
         { 
          //Code to only execute if x seconds have passed since it last executed. 
          if (Trade.AddItem(item.Id)) 
          { 
           itemsAdded++; 
           break; 
          } 
          //end code delay execution 
         } 
        } 
       } 
      } 

그리고 나는 항목이 추가 될 때, 나는 항목이 추가 된 서버에서 확인을받을 필요가 있기 때문에, 그것을 잠을 싶지 않아요.

답변

2

간단한 시간 비교는 어떻습니까?

var lastExecution = DateTime.Now; 

if((DateTime.Now - lastExecution).TotalSeconds >= 3) 
... 

트레이드 클래스에 'lastExecution'을 저장할 수 있습니다. 물론 3 초가 경과하지 않은 경우이 솔루션으로 코드 블록이 호출되지 않습니다 (항목이 추가되지 않음).

은 - 타이머와 // ---------------------------------

다른 솔루션 : 우리는 프로그래밍 방식으로 Windows Forms 타이머 구성 요소를 추가합니다. 이 솔루션을 사용한다면 당신은 그냥 빨리하지, 매번 실행하는 코드가 필요합니다 ;-)

//declare the timer 
private static System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer(); 


//adds the event and event handler (=the method that will be called) 
//call this line only call once 
tmr.Tick += new EventHandler(TimerEventProcessor); 

//call the following line once (unless you want to change the time) 
tmr.Interval = 3000; //sets timer to 3000 milliseconds = 3 seconds 

//call this line every time you need a 'timeout' 
tmr.Start();   //start timer   


//called by timer 
private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) 
{ 
    Console.WriteLine("3 seconds elapsed. disabling timer"); 
    tmr.Stop(); //disable timer 
} 
+0

프로그래머 지옥에 종료됩니다. 그 말이 맞는다면? 서버를 확인하고 수락하고 확인을 다시 보내기 위해 기다려야합니다. 그리고 나는 그것들을 금식에 첨가하기를 원하지 않는다. – Coffman34

+2

응답을 기다릴 필요가 있다면 시간에 의존하지 말고 [대기열] (http://www.dotnetperls.com/queue)을 만드십시오. 서버와 통신하는 백그라운드 스레드는 첫 번째 '명령'을 보내고 다음 '명령'으로 응답을받을 때까지 기다린 다음 대기열에서 다음 '명령'을 전송합니다. (모든 네트워크/i-net 통신이 있어야하므로 백그라운드 스레드에서이 작업을 수행 할 것입니다.) – flexo

1
 DateTime? lastCallDate = null; 
     foreach (int id in allItems) 
     { 
      if (offered > 0 && itemsAdded != (offered * 3) && tDown) 
      { 
       List<Inventory.Item> items = Trade.MyInventory.GetItemsByDefindex(id); 
       foreach (Inventory.Item item in items) 
       { 
        if (!Trade.myOfferedItems.ContainsValue(item.Id)) 
        { 
         //execute if 3 seconds have passed since it last execution... 
         bool wasExecuted = false; 
         while (!wasExecuted) 
         { 
          if (lastCallDate == null || lastCallDate.Value.AddSeconds(3) < DateTime.Now) 
          { 
           lastCallDate = DateTime.Now; 
           if (Trade.AddItem(item.Id)) 
           { 
            itemsAdded++; 
            break; 
           } 
           wasExecuted = true; 
          } 
          System.Threading.Thread.Sleep(100); 
         } 
        } 
       } 
      } 
     } 
관련 문제