Tuesday, 2 April 2024

Calling Async Method from Sync Method in C#

Leave a Comment

Asynchronous programming has grown in importance in today's world of software development, especially for systems that must be scalable and responsive. Therefore, integrating asynchronous functionality into synchronous codebases or frameworks that already exist may be necessary. Calling asynchronous methods from synchronous ones is standard C# procedure. In this post, we'll examine practical strategies for accomplishing this.



Using C# for Asynchronous Programming

Asynchronous programming in C# enables methods to execute concurrently without blocking the caller thread. This is especially useful for I/O-bound operations such as file I/O, network connectivity, and database access. Asynchronous methods that return a Task or a Task that describes the current operation are typically identified by the async modifier.


Using Task.Run()

Task.Run() to execute the async method on a ThreadPool thread and then synchronously wait for its completion.

public void MyNonAsyncMethod()
{
    int result = Task.Run(async () => await MyAsyncMethod()).Result;
    Console.WriteLine(result);
}

Example

using System;
using System.Threading.Tasks;

class Program
{
    public static void Main(string[] args)
    {
        SynchronousWork();
        Console.ReadLine();
    }

   public static void SynchronousWork()
    {
        Console.WriteLine("Synchronous work started...");
        Task.Run(async () =>
        {
            await AsynchronousWorkAsync();
            Console.WriteLine("Asynchronous work completed.");
        }).Wait();
        Console.WriteLine("Synchronous work completed.");
    }

   public static async Task AsynchronousWorkAsync()
    {
        Console.WriteLine("Asynchronous work started...");
        await Task.Delay(2000); // Simulating asynchronous operation
    }
}
SynchronousWork Method

Initiates synchronous work. Inside this method, an asynchronous operation is invoked using Task.Run(). Task.Run() queues the specified work to run on the ThreadPool. Inside the lambda expression, await is used to wait for the asynchronous method AsynchronousWorkAsync() to complete. .Wait() ensures that the asynchronous operation completes before moving to the next line. This approach effectively blocks the synchronous method until the asynchronous operation finishes.

Best ASP.NET Core 8.0.1 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

0 comments:

Post a Comment