0

In case a method takes too long it would make sense to terminate it after a timeout.

Is it possible to implement Method like BreakMyMethod_afterTimeout?

    public static void MyMethod()
    {
            //some code     
    }

    public static async void BreakMyMethod_afterTimeout(int timeoutInSec)
    {
        //break MyMethod after timeout          
    }


    public static void main()
    {
        BreakMyMethod_afterTimeout(60);   //Is this possible to relize?
        MyMethod();
        //the program continues here after 60 seconds at the latest
    }
Denis_
  • 11
  • 1
  • 10
    Give it a `CancellationToken` that the method itself can check for cooperative cancellation. Otherwise, no -- you cannot safely interrupt code that isn't designed to be interrupted. The best you can do then is abandon it and ignore any results, but that can lead to unwanted side effects (like resource exhaustion or threading violations). – Jeroen Mostert Apr 08 '21 at 15:16
  • Does this answer your question? [Asynchronously wait for Task to complete with timeout](https://stackoverflow.com/questions/4238345/asynchronously-wait-for-taskt-to-complete-with-timeout) – Sinatr Apr 08 '21 at 15:23
  • Please prefer `async Task` over `async void` unless it is an event handler. – Peter Csala Apr 09 '21 at 09:03

0 Answers0