I'm following this thread to make some of my commands Async while others sync but I'm having some trouble.
This is what I have so far.
An interface:
public interface ICommand { public Task ExecuteAsync(); } Which I implement in a Wait Command which should be synchronous.
public class WaitCommand : ICommand { public Task ExecuteAsync() { Console.WriteLine("Sleeping..."); Thread.Sleep(5000); Console.WriteLine("Waking up..."); return Task.CompletedTask; } } And another command that does work and should be assynchronous.
public class ConcreteCommand : ICommand { public async Task ExecuteAsync() { await Task.Run(() => { Console.WriteLine("Starting..."); Thread.Sleep(1000); Console.WriteLine("Ending..."); }); } } Then I have some sort of method to read a string and convert it to a command:
public async Task ExecuteAsync(string commandName) { ... get command await command.ExecuteAsync(); } And finally I have a loop
List<string> commands = new List<string> { "concreteCommand", "wait", "concreteCommand" }; foreach (String command in commands) { await commandDispatcher.ExecuteAsync(command); } This is what it prints.
Starting... Ending... Sleeping... Waking up... Starting... Ending... Which means it's not running asynchronously. What's wrong in my implementation?