Simple method for calling async method in standard function in C#

Due to a need to support older versions of .NET code and applications, you may find yourself staring at the need to call an async function from a standard synchronous function, and you don’t want to (or have the time for more likely) to go back and retrofit all of the calling functions with async/await functionality. Well brother, do I have a deal for you.

Here is how you can call the SendGrid SendEmailAsync function from within a regular C# function, and still be able to inspect the result of the task that runs the async method:

public bool SendPlainTextEmail(string subject, string body, List<string> toAddresses)
{
    try
    {
        var apiKey = "Nice try Chachi, go ahead and insert your own SendGrid API key here";
        var client = new SendGridClient(apiKey);
        var from = new EmailAddress("your_verified_sender_email_address@sbemail.com", "Your verified SendGrid email sender name here");
        var to = toAddresses.Select(x => new EmailAddress(x)).ToList();
        var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, to, subject, body, string.Empty);
 
        // Call the async function here and just wait for the results, no async function decorations required
        var task = Task.Run(async () => await client.SendEmailAsync(msg).ConfigureAwait(false));
        var result = task.Result.IsSuccessStatusCode;
        return result;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

I leave it up to you, the reader, to adapt this code for your own purposes, nefarious or otherwise. Regardless, the important stuff is happening with these two lines, which I have boiled down from above to remove the SendGrid cruft:

var task = Task.Run(async () => await theAsyncMethod());
var result = task.Result;
// do something here with the result

In the interest of full disclosure, keep in mind you may need to do this import at or near the top of your source code file to be able to use the Task object in .NET:

using System.Threading.Tasks;

BTW, Happy Birthday to Seth MacFarlane, I can’t wait for season 3 of The Orville, March of 2022 can’t come soon enough.

Leave a Reply