0

My MVC4 application was re-factored to introduce some asynchronous code. However, there are several .ascx and .aspx files that are invocation asynchronous methods. For example,

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeModel>" %>
<div id="connection-config-settings">
    <%
        var authorizationContext = this.AuthorizationContext();
        if (await authorizationContext.ConfigurationAuthorization.CanUserUpdateConfig())
        {
     %>
             <pre>The user can update configuration</pre>
      <% }
         else
         {
       %>
             <pre>The user can NOT update configuration</pre>
       <%
         }
       %>
</div>

Not surprisingly I am getting an error saying that await can only be used inside of a method marked with 'async'. I really do not want to block the async call by using GetAwaiter().GetResult() or .Result or those other hacks. I have been reading a lot about best practices for async programming and the following two resources strongly suggest to never block an async call.

How to call asynchronous method from synchronous method in C#?

https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

How can I call the async method from my .ascx file?

Rob L
  • 3,073
  • 6
  • 31
  • 61

2 Answers2

0

Async is possible in ASP.NET Web Forms 4.5.

First, move your code to *.aspx(ascx).cs backend.

Second, register your async method like this:

public bool UserCanUpdate = false;

protected void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(UserCanUpdateAsync));
}

private async Task UserCanUpdateAsync()
{
    var authorizationContext = this.AuthorizationContext();
    UserCanUpdate = await authorizationContext.ConfigurationAuthorization.CanUserUpdateConfig();
}

Third, add Control attribute to your Page (Control) directive

<%@ Control Async="true" Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeModel>" %>
aleha_84
  • 8,309
  • 2
  • 38
  • 46
0

The solution I went with was to not make any async calls in the .aspx or .ascx files. Instead load the data from the async method invocation into ViewData in the asynchronous controllers and you bypass the problem all together.

Rob L
  • 3,073
  • 6
  • 31
  • 61