How to run async method inside sync method in asp.net | Code2night.com
Code2night
  • Home
  • Blogs
  • Guest Posts
  • Tutorial
  • Post Blog
  • Register
  • Login
  1. Home
  2. Blogpost

How to run async method inside sync method in asp.net

Date- Jan 28,2024

2030

Free Download Pay & Download
Async Methods


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.

Comments

Tags

LinkedinLogin
LinkedinProfile
GetLinkedinProfile
C#
Aspnet
MVC
Linkedin
ITextSharp
Export to Pdf
AspNet Core
AspNet
View to Pdf in Aspnet
Model Validation In ASPNET Core MVC 60
Model Validation
Model Validation In ASPNET Core MVC
Model Validation In ASPNET
Image Compression in AspNet
Compress Image in c#
AspNet MVC
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1210
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp Join Us On Facebook

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Panipat
  • info@Code2night.com

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2025 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Terms & Conditions
  • Refund Policy
  • About Us
  • Privacy Policy
  • Json Beautifier
  • Guest Posts