Home > Software engineering >  Async function causing issues when called as a sync function
Async function causing issues when called as a sync function

Time:05-28

I have a program that sends messages to a Discord server via webbooks

try 
{
  //Send Notification To Bot That Link Has Been Updated
  DiscordWebhookClient notificationBot = new DiscordWebhookClient(WEBHOOK_URL_NB);
  notificationBot.SendMessageAsync("Date: "   DateTime.Now.ToString("MM/dd/yyyy")   " Time: "   DateTime.Now.ToString("hh:mm:ss tt")   " | "   folderName   " | "   "Link Has Been Updated!");
  notificationBot.Dispose();
  Console.WriteLine("LINK HAS BEEN SENT TO DISCORD!", Color.Green);
} 
catch (Exception e) 
{
  Console.WriteLine("ERROR SENDING LINK TO DISCORD!", Color.Red);
  Console.WriteLine(e   "\n");
}

There is 2 issues. The function that sends the message to the server is a Async Function. As you can see, I am calling it synchronously. I have a bug where once in awhile, my program hits the statement where it says "LINK HAS BEEN SENT TO DISCORD!" but my program did not actually send it to the Discord server.

Two questions:

  1. Is this caused by a Deadlock?
  2. Am I allowed to call this function synchronously? If so, am I doing it right?

I just need some guidance on what is the best way to solve this bug. Thank you!

CodePudding user response:

I think BlyZe's answer is the best. Once you get the hang of Async programming it is actually quite easy.

In newer versions of C# you can change the Main method of a Console app to async like this

using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // other code removed for brevity
        await notificationBot.SendMessageAsync("your msg");
    }
}

If you really want to run it synchronously you can indeed use the following:

notificationBot.SendMessageAsync("your msg").GetAwaiter().GetResult();

There should be no issue with deadlocks.

CodePudding user response:

try
{
    //Send Notification To Bot That Link Has Been Updated
    using (DiscordWebhookClient notificationBot = new DiscordWebhookClient(WEBHOOK_URL_NB))
    {
        await notificationBot.SendMessageAsync("Date: "   DateTime.Now.ToString("MM/dd/yyyy")   " Time: "   DateTime.Now.ToString("hh:mm:ss tt")   " | "   folderName   " | "   "Link Has Been Updated!");
    }
    Console.WriteLine("LINK HAS BEEN SENT TO DISCORD!", Color.Green);
} 
catch (Exception e) 
{
    Console.WriteLine("ERROR SENDING LINK TO DISCORD!", Color.Red);
    Console.WriteLine(e   "\n");
}
  • Related