1

Given: I've a class which manages user storage. Now when creating the class I want to ensure indexes which is a asynchronous method. Currently i just call wait, but i don't feel comfortable to it as I'm a little concerned about unexpected behaviors like hanging threads.

public MongoUserStorage(IMongoDatabase database)
{
    userCollection = database.GetCollection<MongoUser>("Users");
    roleCollection = database.GetCollection<MongoUserRole>("UserRoles");

    CreateIndexesAsync().Wait();
}

Question:

What is best way to handle this asynchous mehtod? (I want to be sure that the indexes are present after the class is instantiated)

Just do: CreateIndexesAsync().Wait();

or

var task = CreateIndexesAsync();
task.ConfigureAwait(false);
task.Wait();

Or any better solution ?

2
  • 3
    ConfigureAwait does nothing if used this way. As you may noticed, it returns TaskAwaitable that is supposed to be await-ed instead of the task. The task itself is unaffected. I think you are stuck with what you are doing currently (along with all the related risks). Commented Oct 17, 2015 at 10:32
  • "concerned about unexpected behaviors like hanging threads" I think you should understand the issue first. That allows you to conclude that this is safe. Commented Oct 17, 2015 at 14:16

1 Answer 1

3

You are referring to the classic SynchronizationContext deadlock. As long as CreateIndexesAsync does not use a SynchronizationContext which is very unlikely this is completely safe.

Research what ConfigureAwait does and how to use it. Your current usage demonstrates that you don't really know enough. task.ConfigureAwait(false); is a no-op because it creates a new TaskAwaiter and throws it away.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.