0

Consider the following:

public class FooController : Controller
{
    public async Task<ActionResult> Foo()
    {
        await DoSomethingAsync();

        ...

        return View();
    }

    public async Task<ActionResult> Bar()
    {
        await DoSomethingAsync();

        ...

        return View();
    }

    ...
}

This line, await DoSomethingAsync(); is repeated for each action in the controller. It'd be much nicer to do something like:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    await DoSomethingAsync();
}

But, obviously, you can't run an async op in a synchronous method. I could simply force the async op to run sync, but then you end up with the thread being blocked unnecessarily. Short of running this sync, what options do I have?

1

1 Answer 1

1

Unfortunately, ASP.NET MVC does not have asynchronous filters today. ASP.NET WebAPI does have them, and ASP.NET vNext (combining MVC and WebAPI) does have them.

So, for today I'd say you're best off repeating the code, but in the future (near future, hopefully) that could be cleaned up.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm accepting this as it's technically correct, but the link @DavidTansey posted in the comments below my question gave me a workaround.
I completely disagree with both of those workarounds. The entire point of async on ASP.NET is to free up a thread, and the workaround on codeplex uses an extra thread instead. If you absolutely must do it, then OK, but I'd prefer to just use synchronous methods instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.