Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of AsyncTimeout action filter?

Trying to decrease the timeout of a given operation of my controller (let's say it's Index) I annotated it with AsyncTimeout(5000).
Inside that method, the first line is await Task.Delay(10000).
I published that code to azure, guaranteeing that there's no debug="true" but even so, the request runs for 11-13 sec... so, in my opinion that is not how it's supposed to be used...

So, where should i use this attribute?

Details:
Using .net 4.7 (compilation and runtime) and latests asp.net mvc (5.2.3)

like image 549
Leonardo Avatar asked Sep 05 '17 17:09

Leonardo


People also ask

What is AsyncTimeout?

The [AsyncTimeout] attribute specifies a timeout value in milliseconds for the asynchronous operation. The default timeout value is 45 seconds.

What is the primary purpose of using an async controller action?

The asynchronous controller enables you to write asynchronous action methods. It allows you to perform long running operation(s) without making the running thread idle. It does not mean it will take lesser time to complete the action.

When should Async controller actions be used?

You can use asynchronous action methods for long-running, non-CPU bound requests. This avoids blocking the Web server from performing work while the request is being processed. A typical use for the AsyncController class is long-running Web service calls.

What are action filters?

An action filter is an attribute that you can apply to a controller action -- or an entire controller -- that modifies the way in which the action is executed.


1 Answers

You should look to use the overload of Task.Delay that accepts the CancellationToken. The AsyncTimeout will trigger the cancellation in that case. Your code posted is not using a CancellationToken so I wouldn't expect anything different to happen without it.

UPDATE- Quick demo building on your question. This should throw a TaskCanceledException in about 5 seconds instead of waiting for the Task.Delay call of 15 seconds.

[AsyncTimeout(5000)]
public async Task<ActionResult> Index(CancellationToken cancellationToken)
{
    Stopwatch cancellationTimer = Stopwatch.StartNew();
    try
    {                
        await Task.Delay(15000, cancellationToken);
        cancellationTimer.Stop();
        return View();
    }
    catch (Exception e)
    {
         cancellationTimer.Stop();
         Debug.WriteLine($"Elapsed Time {cancellationTimer.ElapsedMilliseconds}");
         throw (e);
    }            
}
like image 89
mcbowes Avatar answered Oct 01 '22 15:10

mcbowes