Search code examples
c#azureazure-cosmosdbazure-cosmosdb-sqlapi

Azure CosmosDB SQL API createDatabaseAsync does not create database


I am using Azure CosmosDB SQL API. I have an Asynchronous task to Connect to my AzureCosmosDB Account and I am trying to create a database through code.

Following is my code Snippet

private async Task ConnectToDocumentDB()
{
this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
Console.WriteLine(client.WriteEndpoint);
Database db = await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "MyDB" });
Console.WriteLine("Response --" + db.Id);           
}

When I view the Client's EndPonit in console to ensure the AzureCosmosDb Connection, I am able to view the correct EndPoint. But when I try to create the Database, it doesn't create database.

The method call to this asynchronous task from main method is as follows

 Program p = new Program();
 p.ConnectToDocumentDB().Wait();

I dont know where I am going wrong.Help me with this issue.

Thanks in advance!


Solution

  • Depending on your applicaiton's context, .Wait() can cause a deadlock when your code reaches an async call.

    You should be using .GetAwaiter().GetResult() so the state machine is properly generated behind the scenes to prevent this issue.