none
Timeout - function RRS feed

  • Question

  • Hello,

    I have a function and would like to throw an exception, if no response comes back. How can I realize?

    void Test()
    {
      
     try 
     {
          functionXY();    // Timeout after 10 seconds
     }
     catch(Exception ex  )
     {
     }
    }


    With best regards Markus 

    Thursday, November 21, 2019 6:23 PM

Answers

  • Hi Markus Freitag, 

    Thanks for your feedback.

    Here’s a complete example based on EckiS’s suggestion.

            static void Main(string[] args)
            {
                try 
                {
                    string result = CheckTimeOut();
                    Console.WriteLine(result);
                } 
                catch(Exception ex) 
                {
                    Console.WriteLine(ex.Message);
                }          
                Console.ReadLine();
            }
            public static string CheckTimeOut()
            {
                var task = Task.Run(() => functionXY());
                if (task.Wait(TimeSpan.FromSeconds(10)))
                    return task.Result;
    
                task.ContinueWith(t => Console.WriteLine(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
                throw new TimeoutException("Timed out");
            }
            public static string functionXY()
            {
                Thread.Sleep(11000);
                return "functionXY's result";
            }
    

    Result:

    If you want to use 'await' feature, you can refer to the following code.

            static async Task Main(string[] args)
            {
                try 
                {
                    string result = await CheckTimeOut();
                    Console.WriteLine(result);
                } 
                catch(Exception ex) 
                {
                    Console.WriteLine(ex.Message);
                }          
                Console.ReadLine();
            }
            public static async Task<string> CheckTimeOut()
            {
                var task = Task.Run(() => functionXY());
                if (task.Wait(TimeSpan.FromSeconds(10)))
                    return await task;
    
                throw new TimeoutException("Timed out");
            }
            public static string functionXY()
            {
                Thread.Sleep(11000);
                return "functionXY's result";
            }

    Beisdes, Here's a reference about await Task<T> and Task<T>.Result.

    What is the difference between await Task<T> and Task<T>.Result?

    Hope it can help you.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Markus Freitag Wednesday, November 27, 2019 8:43 AM
    Tuesday, November 26, 2019 7:33 AM
    Moderator

All replies

  • Hi Markus Freita, 

    Thank you for posting here.

    According to your question, you want to throw the exception when your function is timeout.

    I make a test on my side, and you can refer to it.

            static void Main(string[] args)
            {
                try
                {
                    Thread t = new Thread(functionXY);
                    t.Start();
                    if (!t.Join(TimeSpan.FromSeconds(10)))
                    {
                        t.Abort();
                        throw new Exception("More than 10 secs.");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
    
                Console.ReadLine();
            }
            public static void functionXY()
            {
                Thread.Sleep(11000);
            }

    Result:

    Besides, here’s a related reference may help you.

    How to set timeout for a line of c# code [duplicate]

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, November 22, 2019 2:10 AM
    Moderator
  • Besides, here’s a related reference may help you.

    How to set timeout for a line of c# code [duplicate]


    Hi Xingyu Zhao,

    Thanks for the sample. Looks good your example.

    using System.Threading.Tasks;
    
    var task = Task.Run(() => SomeMethod(input));
    if (task.Wait(TimeSpan.FromSeconds(10)))
        return task.Result;
    else
        throw new Exception("Timed out");

    Could I do that with await async? If yes, how?

    Then could I compare? Which variant is better?

     Thanks in advance.

    With best regards Markus


    Saturday, November 23, 2019 11:46 AM
  • Thread.Abort should not be used (see the Remarks section in MSDN), so your code is better.

    But beware that your code can result in an UnobservedTaskException when SomeMethod throws AFTER 10 seconds. So you should make sure to handle Exceptions either in SomeMethod, or add an Exception handler. And you should use the dedicated Exception type (TimeOutException).
    var task = Task.Run(() => SomeMethod());
    if (task.Wait(TimeSpan.FromSeconds(10)))
        return task.Result;
    
    //we timed out
    //first make sure to handle any exception after timeout. at least log it
    task.ContinueWith(t => Console.WriteLine(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
    //only now throw the timeout
    throw new TimeoutException("Timed out");

    Saturday, November 23, 2019 2:36 PM
  • So you should make sure to handle Exceptions either in SomeMethod, or add an Exception handler. And you should use the dedicated Exception type (TimeOutException).

    Hello EckiS,

    Thanks for your example, your hint. Can you publish a complete example with possible exceptions?

    What do you think about the await feature?

    Thanks for answers in advance.

    Greetings Markus

    Monday, November 25, 2019 12:42 PM
  • Hi Markus Freitag, 

    Thanks for your feedback.

    Here’s a complete example based on EckiS’s suggestion.

            static void Main(string[] args)
            {
                try 
                {
                    string result = CheckTimeOut();
                    Console.WriteLine(result);
                } 
                catch(Exception ex) 
                {
                    Console.WriteLine(ex.Message);
                }          
                Console.ReadLine();
            }
            public static string CheckTimeOut()
            {
                var task = Task.Run(() => functionXY());
                if (task.Wait(TimeSpan.FromSeconds(10)))
                    return task.Result;
    
                task.ContinueWith(t => Console.WriteLine(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
                throw new TimeoutException("Timed out");
            }
            public static string functionXY()
            {
                Thread.Sleep(11000);
                return "functionXY's result";
            }
    

    Result:

    If you want to use 'await' feature, you can refer to the following code.

            static async Task Main(string[] args)
            {
                try 
                {
                    string result = await CheckTimeOut();
                    Console.WriteLine(result);
                } 
                catch(Exception ex) 
                {
                    Console.WriteLine(ex.Message);
                }          
                Console.ReadLine();
            }
            public static async Task<string> CheckTimeOut()
            {
                var task = Task.Run(() => functionXY());
                if (task.Wait(TimeSpan.FromSeconds(10)))
                    return await task;
    
                throw new TimeoutException("Timed out");
            }
            public static string functionXY()
            {
                Thread.Sleep(11000);
                return "functionXY's result";
            }

    Beisdes, Here's a reference about await Task<T> and Task<T>.Result.

    What is the difference between await Task<T> and Task<T>.Result?

    Hope it can help you.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Markus Freitag Wednesday, November 27, 2019 8:43 AM
    Tuesday, November 26, 2019 7:33 AM
    Moderator
  • Hi Xingyu Zhao,

    >Hope it can help you.
    Yes and thank you.

    Best regards Markus
    Wednesday, November 27, 2019 8:43 AM