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

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for How to call asynchronous method from synchronous method in C#?

How to Call Asynchronous Methods from Synchronous Methods in C#?

Are you stuck with a synchronous method and wondering how to call asynchronous methods from it? Don't worry, we've got you covered! In this blog post, we will address this common issue and provide you with easy solutions to make your code work seamlessly.

The Challenge

Let's say you have a Foo() method that is declared as public async void Foo(). Now, you want to call this asynchronous method from a synchronous method. But here comes the challenge - all the examples and documentation you've come across so far demonstrate calling async methods within other async methods. But what if your entire program is not built with async methods? Is it even possible? The answer is yes!

The Solution

Option 1: Using Task.Run()

One way to deal with this situation is by using the Task.Run() method. This method allows you to offload the execution of an asynchronous method to a background thread. Here's how you can do it:

public void SyncMethod()
{
    // Calling an asynchronous method from a synchronous method
    Task.Run(async () => await Foo()).GetAwaiter().GetResult();
}

public async Task Foo()
{
    // Your asynchronous logic goes here
    await SomeAsyncMethod();
}

By wrapping the call to Foo() inside Task.Run(), you create a new task that executes the asynchronous method in the background. The GetAwaiter().GetResult() call ensures that the synchronous method waits for the asynchronous method to complete.

Option 2: Using TaskCompletionSource

Another option to call an asynchronous method from a synchronous method is by using TaskCompletionSource. This class allows you to create a custom task and complete it manually. Here's an example:

public void SyncMethod()
{
    // Creating a custom task using TaskCompletionSource
    var taskCompletionSource = new TaskCompletionSource<bool>();
    
    Foo().ContinueWith(task => taskCompletionSource.SetResult(true));
    
    taskCompletionSource.Task.GetAwaiter().GetResult();
}

public async Task Foo()
{
    // Your asynchronous logic goes here
    await SomeAsyncMethod();
}

In this approach, we create a new TaskCompletionSource<bool> to represent the completion of our asynchronous method. We then use the ContinueWith() method to set the result of the task when Foo() completes. Finally, we wait for the task to complete by calling GetAwaiter().GetResult().

Summary

Calling asynchronous methods from synchronous methods in C# is indeed possible, despite the lack of examples in the documentation. You have learned two easy solutions to tackle this challenge:

  1. Use Task.Run() to execute the asynchronous method on a background thread.

  2. Utilize TaskCompletionSource to create a custom task and manually complete it.

Now, you have the knowledge and tools to make your code work seamlessly, regardless of the mixture of synchronous and asynchronous methods in your program.

Remember, in modern software development, asynchronous programming is crucial for performance and user experience. Embrace the power of asynchronous methods while keeping your codebase coherent and efficient.

Your Turn

Have you faced challenges calling asynchronous methods from synchronous methods? How did you solve them? Let us know in the comments below. We would love to hear your experiences and solutions!

So go ahead, try out these solutions in your code, and unleash the potential of asynchronous programming in your applications. Happy coding! 😄🚀

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my