2014-04-02 12 views
2

나는 루프가 while입니다. 나는 2의 경우이 잠시 밖으로 나오하려는 : 내가 찾은타이머를 내부에서 설정하는 동안

  1. 나는 그것이 내가 날짜 startTime을 설정할 수 있다는 사실을 알고

를 찾을 이상 10 초 걸렸다

  • 를 필요

      DateTime start = DateTime.Now; 
          while (Find == false) 
          { 
           //code 
    
           if()Find=true; 
           DateTime end = DateTime.Now; 
           if(end-start>10)Find=true; 
          } 
    

    을하지만 더 우아한 결정을 찾고 있어요 : 및 동안 이전과 같이, 내부 때 NowTime -startTime > 10000을 확인합니다.

  • 답변

    0

    이 당신을 위해 무엇을 찾고있는 경우 나도 몰라,하지만 난 열고 System.Diagnostics 네임 스페이스에서 스톱워치 클래스와 함께 갈 것입니다 :

    static class Program 
    { 
        private static readonly Random Rnd = new Random((int)DateTime.UtcNow.Ticks); 
    
        static void Main(string[] args) 
        {    
         var stopwatch = new Stopwatch(); 
    
         stopwatch.Start(); 
         bool isFound; 
         while (true) 
         { 
          isFound = Find(); 
    
          if (isFound || stopwatch.Elapsed.TotalSeconds >= 10) 
           break; 
         } 
    
         Console.WriteLine("Is found: {0}, Spent time: {1} sec(s)", isFound, stopwatch.Elapsed.TotalSeconds); 
         Console.ReadLine(); 
        } 
    
        private static bool Find() 
        { 
         return Rnd.Next(1000) >= 999; 
        } 
    } 
    
    1

    검색 로직 (예제의 "// code"부분)이 실행되는 데 10 초 이상 걸리면 완료 될 때까지 테스트에 도달하지 않기 때문에 코드 샘플이 작동하지 않습니다.

    당신이해야 할 일은 별도의 스레드에서 작업을 실행하고이 스레드에서 시간 초과를 사용하는 것입니다.

    :

    public void MyMethod() 
        { 
         var findThread = new Thread(Find); 
         findThread.Start(); 
    
         if (!findThread.Join(TimeSpan.FromSeconds(10))) 
         { 
          findThread.Abort(); 
          Debug.WriteLine("Find timeout occured"); 
          // Handle find timeout 
         } 
        } 
    
        private static void Find() 
        { 
         //Thread.Sleep(TimeSpan.FromSeconds(5)); 
         Thread.Sleep(TimeSpan.FromSeconds(20)); 
    
         Debug.WriteLine("Find succeeded"); 
        } 
    

    주석 Thread.Sleep(TimeSpan.FromSeconds(5)) 라인 (Thread.Sleep 및 다른 주석) 찾기 방법은 10 초 이하로 실행할 때 예상대로 작동하는지 확인.

    +0

    예제를 추가하십시오. – yorah

    +0

    그것은 단지 (나는 "//코드"부분) 덜 0.5 초 걸릴 것입니다하지만 난 그나마 10 초 이상을 실행 못해 알아요 examlpe의 –

    0

    이 매우 일반적인 상황, 그래서이 과정을 제공하고 있습니다 직접 내 코드에서 : 시간이 경과하기 전에 루프를 완료 한 경우

    public delegate Boolean WaitTestDelegate(); 
    public static Boolean WaitUntil(WaitTestDelegate testDelegate, 
        Int32 milliseconds = 10000, Int32 pariodDuration = 10) 
    { 
        DateTime startTime = DateTime.Now; Double timeSpan = 0; 
        while (!testDelegate() && 
         (timeSpan = (DateTime.Now - startTime).TotalMilliseconds) < milliseconds) 
         Thread.Sleep(pariodDuration); 
        return timeSpan < milliseconds; 
    } 
    

    절차 true를 반환합니다.

    milliseconds은 총 대기 시간입니다.

    periodDurationtestDelegate이 주기적으로 호출되기까지 대기하는 시간입니다.

    WaitUntil(() => { return Find; }); 또는

    WaitUntil(() => Find);는 비동기 대기를해야하는 경우 :

    () => { return Find; } 
    
    마지막으로

    , 코드에서이 프로 시저를 호출 :

    testDelegate

    는 예를 들어, 테스트 코드를 넣을 수 있습니다 방법입니다 , 스레드를 만들고 스레드로 코드를 실행하지만, 그건 다른 이야기입니다.

    관련 문제