Search code examples
c#discord.net

Task.Delay(-1) and GetAwaiter() in Discord bot


    static void Main(string[] args)
{

    Console.OutputEncoding = Encoding.Unicode;
    new Program().MainAsync().GetAwaiter().GetResult();
}

private DiscordSocketClient _client;


public async Task MainAsync()
{
    _client = new DiscordSocketClient();
    _client.Log += Log;
    _client.MessageReceived += _client_MessageReceived;

    var token = File.ReadAllText("token.txt");

    await _client.LoginAsync(TokenType.Bot, token);
    await _client.StartAsync();

    await Task.Delay(-1);
}

Hello guys, just wanna say that im new to programming so i hope who read this post please go easy on me. So i've been trying to make a Discord bot and i got confused at the new Program().MainAsync().GetAwaiter().GetResult(); i've tried to google every parts of the statement and here's what i got, so the youtuber i watched wants to call the non-static MainAsync in the static Main() and the GetAwaiter().GetResult() will wait for the MainAsync method to be completed.

But i don't really understand the await Task.Delay(-1) and the GetAwaiter(), hope someone can tell me why he uses GetResult() with await Task.Delay(-1) and what's GetAwaiter(), thanks.


Solution

  • Task.Delay(-1) blocks the process from exiting

    Task.GetAwaiter().GetResult() is equivalent to await task and is used when the method cannot be marked with async, in this case, the Main method. this is not recommended read here for more