Josh
Josh

Reputation: 662

Why does this code ignore the await and proceed anyway?

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?

Upvotes: 1

Views: 123

Answers (2)

eyalsn
eyalsn

Reputation: 329

Not sure what you are trying to achieve by all these awaits... I would try to keep it simple by having a synchronously method which initializes things, and then another MethodAsync which returns a Task and I can await on that task:

    public async void Index()
    {
        await InitializeIndexAsync();
    }

    private Task InitializeIndexAsync()
    {
        return Task.Factory.StartNew(() => InitializeIndex());
    }

    private void InitializeIndex()
    {
        State = IndexState.Initializing;
        // Initialize other things synchronously.
        IndexAsync().Wait();

        State = IndexState.Ready;
    }

I hope this is what you meant.

Upvotes: 0

Stephen Cleary
Stephen Cleary

Reputation: 456407

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;
}

Upvotes: 4

Related Questions