how do set a timeout for a method

前端 未结 8 1328
情书的邮戳
情书的邮戳 2020-12-25 15:10

how do set a timeout for a busy method +C#.

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-25 16:09

    Ok, here's the real answer.

    ...
    
    void LongRunningMethod(object monitorSync)
    {
       //do stuff    
       lock (monitorSync) {
         Monitor.Pulse(monitorSync);
       }
    }
    
    void ImpatientMethod() {
      Action longMethod = LongRunningMethod;
      object monitorSync = new object();
      bool timedOut;
      lock (monitorSync) {
        longMethod.BeginInvoke(monitorSync, null, null);
        timedOut = !Monitor.Wait(monitorSync, TimeSpan.FromSeconds(30)); // waiting 30 secs
      }
      if (timedOut) {
        // it timed out.
      }
    }
    
       ...
    
    
    

    This combines two of the most fun parts of using C#. First off, to call the method asynchronously, use a delegate which has the fancy-pants BeginInvoke magic.

    Then, use a monitor to send a message from the LongRunningMethod back to the ImpatientMethod to let it know when it's done, or if it hasn't heard from it in a certain amount of time, just give up on it.

    (p.s.- Just kidding about this being the real answer. I know there are 2^9303 ways to skin a cat. Especially in .Net)

    提交回复
    热议问题