I have the following code:
public Index () {
InitializeIndexAsync();
}
async Task InitializeIndexAsync () {
State = IndexState.Initializing;
await Task.Factory.StartNew(async () => {
// Initialize other things.
await IndexAsync();
});
State = IndexState.Ready;
}
I would expect that "State = IndexState.Ready" would not be hit until the asynchronous lambda completes, but debugging shows that line is hit long before the thread started above it completes. Why is this?
StartNew
does not understand async
lambdas, so when you pass it an async
lambda, it will return a Task<Task>
. Conceptually, the "outer" task only represents the start of the async
lambda; the "inner" task represents the completion of the async
lambda.
This is one of the reasons that StartNew
is the wrong choice for async
code, as I explain on my blog. A better solution is to use Task.Run
, which was designed with async
in mind:
async Task InitializeIndexAsync () {
State = IndexState.Initializing;
await Task.Run(async () => {
// Initialize other things.
await IndexAsync();
});
State = IndexState.Ready;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments