Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set timeout for a line of c# code [duplicate]

Tags:

c#

timeout

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.

like image 945
Hossein Avatar asked Nov 22 '12 13:11

Hossein


People also ask

What is setTimeout() in javascript?

setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.


1 Answers

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"); 
like image 149
Carsten Avatar answered Sep 24 '22 16:09

Carsten