c# - Tasks on Framework 4.0: Put a timeout on the innermost task in a chain of continuations -


i looking task based way detect timeout task, without having wait() it.

the timeout should put on innermost task in chain of continuations, while exception should caught @ outermost level.

my solution, instead of blocking execution, returns task wraps original one, allowing user catch exception in case of time out.

so came code:

public static task<t> timeout<t>(task<t> basetask,  int milliseconds) {     var timer = delay(milliseconds);      return task.factory.continuewhenany(         new []         {             basetask,             timer.continuewith<t>(x => { throw new tasktimeoutexception(); })         },         x => x.result     ); } 

the function delay() described in accepted solution @ how put task sleep (or delay) in c# 4.0? .

i improve code, have few questions:

  • can see possible pitfalls?
  • should timeout cause cancellation of original task?

thank you.

edit

based on comments developed slight improvement:

public static task<t> timeout<t>(task<t> basetask,  int milliseconds) {     var timer = delay(milliseconds);      return task.factory.continuewhenany(         new []         {             basetask,             timer         },         x =>         {             if (x.equals(basetask)) return basetask.result;             throw new tasktimeoutexception();         }     ); } 

class program     {         static bool continuerun = true;         static void main(string[] args)         {             system.appdomain.currentdomain.unhandledexception += unhandledexceptiontrapper;              try             {                 console.writeline("enter code");                 task.run(() =>                 {                     console.writeline("enter task");                     system.threading.thread.sleep(1000);                     console.writeline("end thread sleep");                     throw new exception("inner task execution");                 });                 console.writeline("exit code");             }             catch (exception err)             {                 console.writeline("exception code");             }                         {                 console.writeline("finally code");             }               console.writeline("press key exit");             console.readline();         }          private static void unhandledexceptiontrapper(object sender, unhandledexceptioneventargs e)         {             console.write("unhandled exception");             continuerun = false;             console.readline();         }     } 

ouput:

enter code exit  code code press key exit enter task end thread sleep 

in visual studio you'll see raising of 1 uncatched exception


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -