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?
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?
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)
you can use this snippet
Task t = Task.Factory.StartNew(() => ThirdPartLibraryAPI.Run());
Task.WaitAny(t, miliseconds);