How to set timeout for a line of c# code

Hossein picture Hossein · Nov 22, 2012 · Viewed 108.3k times · Source

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.

Answer

Carsten picture Carsten · Nov 22, 2012

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