0

I am calling a third party library API's Run method as follows

await Task.Factory.StartNew(() => ThirdPartLibraryAPI.Run());

I would like to setup some timeout on this in case this API takes too long. How can I do that?

whoami
  • 1,689
  • 3
  • 22
  • 45
  • Create another task using Task.Delay() and then use Task.WhenAny() to wait on only the first task to complete. More at http://stackoverflow.com/questions/9846615/async-task-whenall-with-timeout – sudheeshix Jan 09 '15 at 19:47
  • I am not sure how that applies in this case as I just have one task. May be if you can post an answer with code? – whoami Jan 09 '15 at 19:52

2 Answers2

2

Here is a code snippet:

        var timeoutTask = Task.Delay(1500);
        //using .ContinueWith(t => /*stuff to do on timeout*/);
        //will cause the code to execute even if the timeout did not happen.
        //remember that this task keeps running. we are just not waiting for it
        //in case the worker task finishes first.

        var workerTask = Task.Run(() => { ThirdPartLibraryAPI.Run() });
        var taskThatCompletedFirst = await Task.WhenAny(timeoutTask, workerTask);

        //stuff to do on timeout can be done here
        //if (taskThatCompletedFirst == timeoutTask)
sudheeshix
  • 1,541
  • 2
  • 17
  • 28
1

you can use this snippet

Task t = Task.Factory.StartNew(() => ThirdPartLibraryAPI.Run());
Task.WaitAny(t, miliseconds);
Patrick
  • 736
  • 9
  • 27