The code
Ο κώδικας
What is the compile time type of each variable?
Ποιος είναι ο τύπος κάθε μεταβλητής κατά το compile;
var t1 = Task.Factory.StartNew(() => { DoWork(); });
var t2 = Task.Factory.StartNew(() => 42);
var t3 = Task.Factory.StartNew(async () => { await X(); });
var t4 = Task.Factory.StartNew(async () => { await X(); return 42; });
var t5 = Task.Run(() => { DoWork(); });
var t6 = Task.Run(() => 42);
var t7 = Task.Run(async () => { await X(); });
var t8 = Task.Run(async () => { await X(); return 42; });
Run it yourself:
Τρέξ' το μόνος σου:
The answer
Η απάντηση
t1 Task
t2 Task<int>
t3 Task<Task> // trap
t4 Task<Task<int>> // trap
t5 Task
t6 Task<int>
t7 Task
t8 Task<int>
Why
Γιατί
For synchronous lambdas both methods give the same types. The difference shows up only with async lambdas. An async lambda returns a Task or Task<int>. StartNew wraps that in another task. Task.Run has overloads for Func<Task> and Func<Task<TResult>> that unwrap it.
With t4, await t4 gives you a Task<int>, not an int. You need await await t4 or t4.Unwrap() to get the 42.
Με synchronous lambdas οι δύο μέθοδοι δίνουν τους ίδιους τύπους. Η διαφορά φαίνεται μόνο με async lambdas. Ένα async lambda επιστρέφει Task ή Task<int>. Το StartNew το τυλίγει σε άλλο ένα task. Το Task.Run έχει overloads για Func<Task> και Func<Task<TResult>> που το ξετυλίγουν.
Με το t4, το await t4 σου δίνει ένα Task<int>, όχι ένα int. Χρειάζεσαι await await t4 ή t4.Unwrap() για να πάρεις το 42.
Remember
Να θυμάσαι
StartNew plus async lambda without Unwrap(): assume a bug until proven otherwise.
StartNew με async lambda χωρίς Unwrap(): υπόθεσε ότι υπάρχει bug μέχρι να αποδειχθεί το αντίθετο.