Fábio Antunes
Fábio Antunes

Reputation: 17174

Wait as long for 100 milliseconds for data returned from method else throw exception

How can i have any kind of data returned from a method or property within a time frame, and if any data is returned within that time frame an exception is thrown?

Pretty much I have a simple method that will perform a simple task, once performed the method returns a value, and if any value is returned within 100 milliseconds I want that the method be aborted and an exception be thrown, for instance a TimeoutException for example, any kind of exception, as long it does the task.

Upvotes: 3

Views: 504

Answers (5)

Ani
Ani

Reputation: 113462

If you are on .NET 3.5 and can't use Parallel Extensions, you can use asynchronous delegates. This has the added benefit of rethrowing exceptions thrown by the method on the calling thread. The timeout logic in this example relies on a WaitHandle, as mentioned by leppie.

public static T EvaluateAsync<T> (this Func<T> func, Timespan timeout)
{
  var result = func.BeginInvoke(null, null);

  if (!result.AsyncWaitHandle.WaitOne(timeout))
       throw new TimeoutException ("Operation did not complete on time.");

  return func.EndInvoke(result);
}

static void Example()
{
   var myMethod = new Func<int>(ExampleLongRunningMethod);

  // should return
  int result = myMethod.EvaluateAsync(TimeSpan.FromSeconds(2));

  // should throw
  int result2 = myMethod.EvaluateAsync(TimeSpan.FromMilliseconds(100));
}

static int ExampleLongRunningMethod()
{
  Thread.Sleep(1000);
  return 42;
}

Upvotes: 5

Brian Rasmussen
Brian Rasmussen

Reputation: 116471

If you have access to .NET 4 I suggest you take a look at the new Task class. Create a Task with the work you want done and start this. The Wait method allows you to specify a timeout value. Wait returns a bool, so you know if the timeout occurred or not.

Upvotes: 8

VinayC
VinayC

Reputation: 49235

Well - you can start the method on a different thread and if thread does not return within stipulated time-frame then abort it. Although, if you are looking at very small time-frames then this way will have large overhead involved. (BTW, you can use Thread.Join overload for waiting stipulated time).

Upvotes: 0

leppie
leppie

Reputation: 117330

Look at WaitHandle and it's derivations. Should do what you want.

Upvotes: 2

Related Questions