How to run async method inside sync method in asp.net
Running Async Method Inside Sync Method in ASP.NET MVC
This article explains a code example demonstrating how to run an asynchronous method inside a synchronous method in an ASP.NET MVC application.
1. Index Action Method
The Index
action method is the default method that gets called when the corresponding view is requested. It calls the SynchronousMethod
and then returns the default view.
2. SynchronousMethod
The SynchronousMethod
is a static method that demonstrates running an asynchronous task within a synchronous context. It logs messages to the console, creates a list, and uses Task.Run
to run the AsynchronousTask
method asynchronously. It then waits for the asynchronous task to complete using GetAwaiter().GetResult()
.
3. AsynchronousTask
The AsynchronousTask
is the asynchronous task method. It simulates an asynchronous operation by adding items to a list and introducing a delay using Task.Delay
. It returns the list of items.
Task.Run(async () => { // Call the asynchronous task and await its completion list = await AsynchronousTask(); }).GetAwaiter().GetResult();
The key takeaway is that Task.Run
is used in the synchronous method to run the asynchronous task, and await
is used to asynchronously wait for the completion of the task. The example demonstrates how you can work with asynchronous code in an ASP.NET MVC application. However, it's worth noting that in a real-world scenario, you would typically leverage asynchronous patterns throughout the application to avoid blocking the main thread.
Code Example
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace TaskDemo.Controllers
{
public class HomeController : Controller
{
// Action method for the default view
public ActionResult Index()
{
// Call the synchronous method
SynchronousMethod();
return View();
}
// Synchronous method
public static void SynchronousMethod()
{
// Log that the synchronous method has started
Console.WriteLine("Synchronous method starts...");
// Create a list to store results
var list = new List<string>();
// Asynchronous task inside a synchronous method using Task.Run
Task.Run(async () =>
{
// Call the asynchronous task and await its completion
list = await AsynchronousTask();
}).GetAwaiter().GetResult();
// Log that the synchronous method continues
Console.WriteLine("Synchronous method continues...");
}
// Asynchronous task method
public static async Task<List<string>> AsynchronousTask()
{
// Create a list to store results
var list = new List<string>();
// Log that the asynchronous task has started
Console.WriteLine("Asynchronous task starts...");
// Simulate an asynchronous operation (e.g., fetching data from a database)
for (var i = 0; i < 100; i++)
{
list.Add("Item " + i.ToString());
}
await Task.Delay(2000); // Simulate a delay of 2000 milliseconds (2 seconds)
// Log that the asynchronous task has completed
Console.WriteLine("Asynchronous task completes...");
// Return the list of results
return list;
}
// Action method for the "About" view
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
// Action method for the "Contact" view
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
So this is how we can call async methods inside sync methods in asp.net application.