Reputation: 1467
Consider the following code
async Task<int> foo()
{
await Task.Delay(1000);
return 42;
}
...
// OPTION 1
Task t = Task.Factory.StartNew(foo,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
t.Wait();
...
// OPTION 2
Task t = foo();
t.Wait()
The questions
what is the substantial difference between two calling options?
In option 1. Suppose I override the default TaskScheduler. For await in foo method - which TaskScheduler will be used? Will it use the default or the one passed in parameter to father task?
Upvotes: 4
Views: 2922
Reputation: 564451
In general, though, the "option 1" will create a new Task that wraps the call to foo()
, effectively making a Task<Task<int>>
. When you call .Wait()
on it, it will not wait for the inner task to complete, since the inner task will return nearly immediately (as soon as the Task.Delay
) is hit.
As to your question about using a non-default TaskScheduler
, in general, it won't change the behavior, except for the fact that it may block until the custom scheduler starts the task. Without more information about the scheduler in question, it's impossible to know exactly what would happen.
The second option, however, will block until the delay is completed, as it will start the task, and block until after the delay is completed.
Upvotes: 3