Link to asynchronous tasks in the C # dictionary

I ran into a problem related to asynchronous tasks in a dictionary in a couple of programs, and I cannot plunge into my head how to solve it.

I have an asynchronous task that looks like this:

MessageEventArgs.Channel.SendMessage("somestring");

MessageEventArgs is a class from a third-party library that I declare statically at the beginning of my program:

public static MessageEventArgs meargs;

The program listens for events in the IRC channel and performs actions based on text commands. Instead of having a giant switch statement for each command, I wanted to make a dictionary that matched the string to the method. Not everyone just sends messages, so I can't just save the line for sending. It looks like this:

public static Dictionary<string, Task> myDict= new Dictionary<string, Task>()
{
    {"!example", MessageEventArgs.Channel.SendMessage("HelloWorld") }
}

In Main (), I call:

MessageReceived += async (s,e) => 
{
     meargs = e;
     await myDict[e.Message.Text];
}

, SendMessage, async. MessageEventArgs , . ? , , , void, async ( ) void Task.

!

+4
2

, IrcCommand ExecuteCommand. , . ExecuteCommand , . ExecuteCommand Channel, .

Dictionary<string, IrcCommand>, Key , Value , .

, IrcCommand ExecuteCommand, Channel .


. , , .

:

public class ExampleCommand : IrcCommand
{
    public override void ExecuteCommand(Channel channel)
    {
        channel.SendMessage("Hello World");
    }
}

public class DisconnectCommand : IrcCommand
{
    public override void ExecuteCommand(Channel channel)
    {
        channel.Disconnect();
    }
}

:

private void RegisterCommands()
{
    _commands.add("!example", new ExampleCommand());
    _commands.add("!disconnect", new DisconnectCommand());
}

:

_commands(commandText).ExecuteCommand(e.channel);
+2

:

public static Dictionary<string, Func<Task>> myDict= new Dictionary<string, Func<Task>>()
{
    {"!example", () => MessageEventArgs.Channel.SendMessage("HelloWorld") }
}

await myDict[e.Message.Text]();
+3

Source: https://habr.com/ru/post/1624328/


All Articles