16

如果同步方法执行时间过长,我正在寻找一种有效的方法来引发超时异常。我看过一些样品,但没有什么能完全符合我的要求。

我需要做的是

  1. 检查同步方法是否超出其 SLA
  2. 如果它确实抛出超时异常

如果同步方法执行时间过长,我不必终止它。(多次故障将使断路器跳闸并防止级联故障)

到目前为止,我的解决方案如下所示。请注意,我确实将 CancellationToken 传递给同步方法,希望它能够在超时时兑现取消请求。我的解决方案还返回一个任务,然后可以根据我的调用代码的需要等待等。

我担心的是这段代码会为每个正在监控的方法创建两个任务。我认为 TPL 会很好地处理这一点,但我想确认一下。

这有意义吗?有一个更好的方法吗?

private Task TimeoutSyncMethod( Action<CancellationToken> syncAction, TimeSpan timeout )
{
  var cts = new CancellationTokenSource();

  var outer = Task.Run( () =>
  {
     try
     {
        //Start the synchronous method - passing it a cancellation token
        var inner = Task.Run( () => syncAction( cts.Token ), cts.Token );

        if( !inner.Wait( timeout ) )
        {
            //Try give the sync method a chance to abort grecefully
            cts.Cancel();
            //There was a timeout regardless of what the sync method does - so throw
            throw new TimeoutException( "Timeout waiting for method after " + timeout );
        }
     }
     finally
     {
        cts.Dispose();
     }
  }, cts.Token );

  return outer;
}

编辑:

使用@Timothy's answer我现在正在使用它。虽然代码并没有显着减少,但它更清晰。谢谢!

  private Task TimeoutSyncMethod( Action<CancellationToken> syncAction, TimeSpan timeout )
  {
    var cts = new CancellationTokenSource();

    var inner = Task.Run( () => syncAction( cts.Token ), cts.Token );
    var delay = Task.Delay( timeout, cts.Token );

    var timeoutTask = Task.WhenAny( inner, delay ).ContinueWith( t => 
      {
        try
        {
          if( !inner.IsCompleted )
          {
            cts.Cancel();
            throw new TimeoutException( "Timeout waiting for method after " + timeout );
          }
        }
        finally
        {
          cts.Dispose();
        }
      }, cts.Token );

    return timeoutTask;
  }
4

4 回答 4

23

If you have a Task called task, you can do this:

var delay = Task.Delay(TimeSpan.FromSeconds(3));
var timeoutTask = Task.WhenAny(task, delay);

If timeoutTask.Result ends up being task, then it didn't timeout. Otherwise, it's delay and it did timeout.

I don't know if this is going to behave identically to what you have implemented, but it's the built-in way to do this.

于 2013-09-03T16:53:09.383 回答
2

.NET 4.0我已经为某些方法不可用的地方重新编写了这个解决方案,例如Delay。此版本正在监视返回的方法object。How to implement Delayin .NET 4.0from here:How to put a task to sleep (or delay) in C# 4.0?

public class OperationWithTimeout
{
    public Task<object> Execute(Func<CancellationToken, object> operation, TimeSpan timeout)
    {
        var cancellationToken = new CancellationTokenSource();

        // Two tasks are created. 
        // One which starts the requested operation and second which starts Timer. 
        // Timer is set to AutoReset = false so it runs only once after given 'delayTime'. 
        // When this 'delayTime' has elapsed then TaskCompletionSource.TrySetResult() method is executed. 
        // This method attempts to transition the 'delayTask' into the RanToCompletion state.
        Task<object> operationTask = Task<object>.Factory.StartNew(() => operation(cancellationToken.Token), cancellationToken.Token);
        Task delayTask = Delay(timeout.TotalMilliseconds);

        // Then WaitAny() waits for any of the provided task objects to complete execution.
        Task[] tasks = new Task[]{operationTask, delayTask};
        Task.WaitAny(tasks);

        try
        {
            if (!operationTask.IsCompleted)
            {
                // If operation task didn't finish within given timeout call Cancel() on token and throw 'TimeoutException' exception.
                // If Cancel() was called then in the operation itself the property 'IsCancellationRequested' will be equal to 'true'.
                cancellationToken.Cancel();
                throw new TimeoutException("Timeout waiting for method after " + timeout + ". Method was to slow :-)");
            }
        }
        finally
        {
            cancellationToken.Dispose();
        }

        return operationTask;
    }

    public static Task Delay(double delayTime)
    {
        var completionSource = new TaskCompletionSource<bool>();
        Timer timer = new Timer();
        timer.Elapsed += (obj, args) => completionSource.TrySetResult(true);
        timer.Interval = delayTime;
        timer.AutoReset = false;
        timer.Start();
        return completionSource.Task;
    }
}

如何在控制台应用程序中使用它。

    public static void Main(string[] args)
    {
        var operationWithTimeout = new OperationWithTimeout();
        TimeSpan timeout = TimeSpan.FromMilliseconds(10000);

        Func<CancellationToken, object> operation = token =>
        {
            Thread.Sleep(9000); // 12000

            if (token.IsCancellationRequested)
            {
                Console.Write("Operation was cancelled.");
                return null;
            }

            return 123456;
        };

        try
        {
            var t = operationWithTimeout.Execute(operation, timeout);
            var result = t.Result;
            Console.WriteLine("Operation returned '" + result + "'");
        }
        catch (TimeoutException tex)
        {
            Console.WriteLine(tex.Message);
        }

        Console.WriteLine("Press enter to exit");
        Console.ReadLine();
    }
于 2014-11-21T13:45:21.833 回答
2

详细说明 Timothy Shields 清洁解决方案:

        if (task == await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(3))))
        {
            return await task;
        }
        else
            throw new TimeoutException();

我发现,此解决方案还将处理 Task 具有返回值的情况 - 即:

async Task<T>

更多内容可以在这里找到:MSDN: Crafting a Task.TimeoutAfter Method

于 2015-06-10T11:34:41.727 回答
1

Jasper 的回答让我得到了大部分的帮助,但我特别想要一个void函数来调用具有超时的非任务同步方法。这就是我最终得到的结果:

public static void RunWithTimeout(Action action, TimeSpan timeout)
{
    var task = Task.Run(action);
    try
    {
        var success = task.Wait(timeout);
        if (!success)
        {
            throw new TimeoutException();
        }
    }
    catch (AggregateException ex)
    {
        throw ex.InnerException;
    }
}

像这样称呼它:

RunWithTimeout(() => File.Copy(..), TimeSpan.FromSeconds(3));
于 2018-03-15T06:06:34.227 回答