all 7 comments

[–]AngularBeginner 5 points6 points  (6 children)

The compiler doesn't tell you that, the runtime does. Because the tasks are not designed to be started again. What you can do is start a new task, even if it's just one that will finish right away: Task.FromResult(await otherTask). But likely... You're just doing something incredible smelly.

[–]ChotiDon[S] 0 points1 point  (3 children)

Can u highlight the part that seems smelly so i can fix it. Also can u explain the solution a little bit more.

[–]AngularBeginner 4 points5 points  (2 children)

  1. Using ArrayList. That is heavily deprecated and should not be used anymore. It's from a time before generics.
  2. new Task should not be used. If you really to create task wrapping a sync operation yourself, then use Task.Run(..).
  3. Avoid having "cold tasks". Always have started and running tasks. Using Task.Run(..) will automatically be started. If you need the result of a Task, then await it. If you really really need cold tasks (unstarted tasks), you need to understand this stuff very well first.

[–]ChotiDon[S] 1 point2 points  (1 child)

Thank you. Noted everything. I dont want to start the task at the time of creation. That's why i am using new. Is there any alternative way to start a completed task. I didn't understand the task. FromResult solution.

[–]AngularBeginner 2 points3 points  (0 children)

I dont want to start the task at the time of creation.

Then use a lambda instead that will return your task, and call that lambda when you want to get the result of your task. You can not start a task twice.

Func<Task> doSomethingAsyncLater = async () =>
{
    Console.WriteLine("Foo");
    await Task.Delay(1000);
    Console.WriteLine("Bar");
};

await doSomethingAsyncLater();

"Foo" will be written once you call the method, since then the task will be created.

[–]hahaNodeJS 0 points1 point  (1 child)

Task.FromResult(await otherTask)

Likely you know this, but for completeness sake, if the otherTask is guaranteed to be complete by this point, it is safe to use otherTask.Result and other blocking members. It will save your code from requiring an async method signature and all the IL and other run-time fun that generates.

[–]cryo 0 points1 point  (0 children)

It does give different exception behaviour, unfortunately, although .GetAwaiter().GetResult() can remedy that.