c# - Monitoring a synchronous method for timeout -


i'm looking efficient way throw timeout exception if synchronous method takes long execute. i've seen samples nothing quite want.

what need

  1. check sync method exceed sla
  2. if throw timeout exception

i not have terminate sync method if executes long. (multiple failures trip circuit breaker , prevent cascading failure)

my solution far show below. note pass cancellationtoken sync method in hope honor cancellation request on timeout. solution returns task can awaited on etc desired calling code.

my concern code creates 2 tasks per method being monitoring. think tpl manage well, confirm.

does make sense? there better way this?

private task timeoutsyncmethod( action<cancellationtoken> syncaction, timespan timeout ) {   var cts = new cancellationtokensource();    var outer = task.run( () =>   {      try      {         //start synchronous method - passing cancellation token         var inner = task.run( () => syncaction( cts.token ), cts.token );          if( !inner.wait( timeout ) )         {             //try give sync method chance abort grecefully             cts.cancel();             //there timeout regardless of sync method - throw             throw new timeoutexception( "timeout waiting method after " + timeout );         }      }           {         cts.dispose();      }   }, cts.token );    return outer; } 

edit:

using @timothy's answer i'm using this. while not less code lot clearer. thanks!

  private task timeoutsyncmethod( action<cancellationtoken> syncaction, timespan timeout )   {     var cts = new cancellationtokensource();      var inner = task.run( () => syncaction( cts.token ), cts.token );     var delay = task.delay( timeout, cts.token );      var timeouttask = task.whenany( inner, delay ).continuewith( t =>        {         try         {           if( !inner.iscompleted )           {             cts.cancel();             throw new timeoutexception( "timeout waiting method after " + timeout );           }         }                 {           cts.dispose();         }       }, cts.token );      return timeouttask;   } 

if have task called task, can this:

var delay = task.delay(timespan.fromseconds(3)); var timeouttask = task.whenany(task, delay); 

if timeouttask.result ends being task, didn't timeout. otherwise, it's delay , did timeout.

i don't know if going behave identically have implemented, it's built-in way this.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

IIS->Tomcat Redirect: multiple worker with default -