Wait 100 milliseconds for the data returned from the else throw exception method

How can I get any data returned by a method or property over a period of time, and if any data is returned during this period of time, an exception is thrown?

To a large extent, I have a simple method that will perform a simple task, after executing the method returns a value, and if any value is returned within 100 milliseconds, I want this method to be interrupted and an exception be thrown, for TimeoutExceptionexample, any exception if it performs the task.

+3
source share
5 answers

.NET 3.5 , . , . - WaitHandle, 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;
}
+5

.NET 4, Task. , , . Wait -. Wait bool, , - .

+8

WaitHandle . , .

+2

Good - you can run the method on another thread, and if the thread does not return in the specified time interval, then cancel it. Although, if you look at a very small time frame, then this method will have a lot of overhead. (BTW, you can use Thread.Join overload for the expected agreed time).

0
source

Source: https://habr.com/ru/post/1761300/


All Articles