Reputation: 12557
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 ?
Upvotes: 1
Views: 284
Reputation: 171178
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.
Upvotes: 3