How to set timeout for a line of c# code

c#, timeout

Solution

You can use the Task Parallel Library. To be more exact, you can use `Task.Wait(TimeSpan)`:

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");

Problem

Possible Duplicate: Set timeout to an operation How can i set timeout for a line of code in c#. For example `RunThisLine(SomeMethod(Some Input), TimeSpan.FromSeconds(10))` run `SomeMethod` with 10 second time out. Thanks in advance.

Original source

Related problems