0

I just started my project and I want to know if it's posibble to do async without tasks and await like I tried to do. This is what I want it to do: I want to wait 2 second and then do something, but if I press 1 on numpad it will skip waiting. This is everything that I have to now:

static async void DelayedWork(int body, int noveBody)
    {
        ConsoleKey consoleKey = Console.ReadKey().Key;
        if (consoleKey == ConsoleKey.NumPad1)
        {
            DoSomething();    
        }
        else
        {
        }
    }

static void Game()
    {
        DelayedWork();
        System.Threading.Thread.Sleep(2000);
        DoSomething();
    }

Is await or task necessary to do this? Because in this phase it doesn't work...

  • Of course you can use [lower-level primitives](http://www.albahari.com/threading/) instead of async/await, but why do you want to? If you're trying to wait on user input you should probably be using a Timer, not a thread. – Dour High Arch Nov 18 '18 at 19:43
  • you will need at least a second thread. up to you if you leave the management of that thread to the async...await mechanism, or roll your own. at the moment you're sleeping on the same thread where you previously look for the keystroke. and Console.ReadKey is a blocking call, there is no parallelity. – Cee McSharpface Nov 18 '18 at 19:44
  • Possible duplicate of [C# Async Task Method Without Await or Return](https://stackoverflow.com/questions/47187544/c-sharp-async-task-method-without-await-or-return) – Anas Alweish Nov 18 '18 at 19:45
  • So I can't do it in parallel... Is there some other way to do it parallel? – Matěj Koumes Strnad Nov 18 '18 at 19:54
  • I need to do it parallel, but I don't know how. – Matěj Koumes Strnad Nov 18 '18 at 20:02

1 Answers1

0

You have two different things you want to do simultaneously. One is to wait for numpad 1. The other is to wait for 2 seconds. Then, you want to do another thing, which is irrelevant to your question. Here is a solution using async/await:

var task1 = Task.Delay(2000);
var task2 = Task.Run(()=>while (Console.ReadKey()!=ConsoleKey.NumPad1){});
await Task.WhenAny(new[] { task1, task2 });

I didn't compile this, so it may have some bugs, but you get the idea, I hope.

Siderite Zackwehdex
  • 6,293
  • 3
  • 30
  • 46