0

I want create a task, which itself calls a async method.

  var task = new Task(async () =>                    {
                        var res = await asyncMethod();   
                        Console.WriteLine("Async");
                    });
  task.start();


Task.WaitAll(task);
Console.WriteLine("Finished");

When running this code "Finished" is returned before "Async". I guess its because the async lambda is executed independendly from the created task. Is it possible in a task to wait for another async method?

J. Doe
  • 522
  • 6
  • 22
  • 1
    Yes, `task` just starts `async() => ...` and that's *all* (*fire and forget* mode), so `task` completes immediately – Dmitry Bychenko Mar 24 '20 at 07:55
  • 1
    Try [this answer](https://stackoverflow.com/a/24777391/1997232). – Sinatr Mar 24 '20 at 07:57
  • 1
    Never use `new Task` and then call `Start` on it – these are mainly intended for internal use. You should use `Task.Run`. – ckuri Mar 24 '20 at 08:13
  • @ckuri But when I use Task.Run the task starts immdedialtly? I want to start several taks at once and before that I create them with my code – J. Doe Mar 24 '20 at 11:59
  • 1
    @J.Doe: Then use `Func`. [There are **zero** use cases for the `Task` constructor](https://blog.stephencleary.com/2014/05/a-tour-of-task-part-1-constructors.html). – Stephen Cleary Mar 25 '20 at 17:02

0 Answers0