Open Mr0N opened 3 weeks ago
Tagging subscribers to this area: @dotnet/area-system-threading-tasks See info in area-owners.md if you want to be subscribed.
The problem is in the repro code. If you have code like this:
var task = new Task(async () =>
{
A();
await Task.Delay(1000);
B();
});
task.Start();
that compiles down to using the Task constructor that takes an Action, with the async lambda becoming an async void
. That Action will return the moment it awaits something that's not yet complete. So in my above example, that Task will complete the moment it hits that await.
The problem is in the repro code. If you have code like this:
var task = new Task(async () => { A(); await Task.Delay(1000); B(); }); task.Start();
that compiles down to using the Task constructor that takes an Action, with the async lambda becoming an
async void
. That Action will return the moment it awaits something that's not yet complete. So in my above example, that Task will complete the moment it hits that await.
I basically understood why it is executed this way. It would be good to add a constructor public Task(Func<Task> action){}
to the Task class so that it would be possible to wait for the task to complete.
In general we discourage use of the Task constructors + Start. Their use is very limited. Task.Run already provides the desired overload; if you use Task.Run instead of the ctor + Start, it should "just work" the way you expect.
The method Task.Run does not have these parameters.
The method Task.Run does not have these parameters.
If you need those options, you can use Task.Factory.StartNew
and call .Unwrap on the result.
Well, plus everything is quite deceptive. For example, the Task.Run method accepts asynchronous lambdas. A user who uses the Task constructor also ideally thinks that it accepts asynchronous lambdas.
The Task class is essentially part of async/await.
A user who uses the Task constructor also ideally thinks that it accepts asynchronous lambdas.
I understand the concern. This is the danger of async void
lambdas.
Description
In the tasks, for some reason, the status shows that they have already been completed, but they are still running. Because of this, Task.WaitAll does not stop them, as it thinks they have already finished. This is a strange behavior.![image](https://github.com/dotnet/runtime/assets/61237140/01657100-77f0-4a38-8721-47cf6fd2b502)
Reproduction Steps
Expected behavior
-
Actual behavior
-
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
No response