Why is my app not waiting when using sleep

47 Views Asked by At

Why is my console app not waiting? All the outputted times are the same.

I app hoping to execute the commands but not all at once I would like for the WaitAfterExecution to finish before executing the next command on so on. But also if I have some long-running tasking fetching data I would also like that to continue.

public class Qsend: IQCommand
{


    public Qsend(Action p, int v1, int v2, string v3)
    {
        OnCommand = p;
        WaitBeforeExecution = v1;
        WaitAfterExecution = v2;
        Name = v3;
    }

  public  Action OnCommand { get ; set ; }
    public int WaitBeforeExecution { get ; set ; }
    public int WaitAfterExecution { get ; set ; }
    public string Name { get ; set ; }
}

public interface IQCommand
{
    Action OnCommand { get; set; }
    int WaitBeforeExecution { get; set; }
    int WaitAfterExecution { get; set; }
    string Name { get; set; }

}

public static class CExtensions
{
    public static void ProcessThis(this IQCommand irc)
    {
        Console.WriteLine("Process This Started!!!");
        if (irc == null)
            return;

        if (irc.OnCommand == null)
            return;

        if (irc.WaitBeforeExecution > 0)
            System.Threading.Thread.Sleep(irc.WaitBeforeExecution);

        irc.OnCommand.Invoke();

        if (irc.WaitAfterExecution > 0)
            System.Threading.Thread.Sleep(irc.WaitAfterExecution);
        Console.WriteLine("Process This End!!!");
    }
}

Usage:

using System.Diagnostics;

List<IQCommand> commands = new List<IQCommand>();

commands.Add(new Qsend(() => { Console.WriteLine($"Command 1 {DateTime.Now.ToString("HH:mm:ss.ffffff")}"); }, 3, 6, "Name 1"));
commands.Add(new Qsend(() => { Console.WriteLine($"Command 2 { DateTime.Now.ToString("HH:mm:ss.ffffff")}"); }, 5, 10, "Name 2"));
// Creating object of ExThread class

Console.WriteLine($"Before EXE {DateTime.Now.ToString("HH:mm:ss.ffffff")}");
foreach (var item in commands)
{
    Console.WriteLine(item.Name);
    item.ProcessThis();
}
Console.WriteLine($"AFTER EXE {DateTime.Now.ToString("HH:mm:ss.ffffff")}");

Output:

Before EXE 15:11:13.482163
Name 1
Process This Started!!!
Command 1 15:11:13.533112
Process This End!!!
Name 2
Process This Started!!!
Command 2 15:11:13.563431
Process This End!!!
AFTER EXE 15:11:13.578287

I Also Tried:

Thread thr = new Thread(new ThreadStart(() => {
    Console.WriteLine($"Before EXE {DateTime.Now.ToString("HH:mm:ss.ffffff")}");
    foreach (var item in commands)
    {
        Console.WriteLine(item.Name);
        item.ProcessThis();
    }
    Console.WriteLine($"AFTER EXE {DateTime.Now.ToString("HH:mm:ss.ffffff")}");
}));
thr.Start();
0

There are 0 best solutions below