Thursday, 28 January 2016

How to use Async keyword in Asp.net? [Solved] with example

Error 1:-
"async void" Page events are unsupported in the current application configuration. To enable this, set the following configuration switch in Web.config:
<system.web>
<httpRuntime targetFramework="4.5" />
</system.web>
For more information, see http://go.microsoft.com/fwlink/?LinkId=252465.

Solution:
<system.web>
<httpRuntime targetFramework="4.5" />
</system.web>

Error 2:-
An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.

Solution:
<%@ Page Language="C#" Debug="true" %>





Complete Example:-

<%@ Page Language="C#" Async="true" %>
<%@ Import Namespace="System.Threading.Tasks" %>
<%@ Import Namespace="System.Threading" %>
<%@ Import Namespace="System.Diagnostics" %>
<script runat="server">
protected async void Page_Load(object sender, EventArgs e)
{
Stopwatch sp = new Stopwatch();
sp.Start();
var loop = 20;
while (loop > 0) {
Response.Write( await calldata(loop.ToString()) );
loop--;
}
Response.Write("Total time taken:" + sp.ElapsedMilliseconds + " ms");
sp.Stop();
}
async Task<string> calldata(string count)
{
System.Threading.Thread.Sleep(500);
var response = DateTime.Now.ToString("HH:mm:ss fff") + " " + Guid.NewGuid().ToString() + "<br/>" ;
var data = await Task.Run<string>(() => response);
return data;
}
</script>