I'm having some dramas with some CosmosDB code I'm trying to implement in a .NET Core console app. I'm trying to add documents to a container but am getting unhandled errors which are quitting my methods without any exception.
Here is a bit of code that's calling the method:
using (StreamReader file = File.OpenText(@"Orgs.json"))
{
JsonSerializer serializer = new JsonSerializer();
List<Org> org1 = (List<Org>)serializer.Deserialize(file, typeof(List<Org>));
foreach (var org in org1)
{
await orgClient.AddItemAsync(org);
}
}
and here is the method:
public async Task AddItemAsync(T item)
{
try
{
Type myType = item.GetType();
PropertyInfo propertyInfo = myType.GetProperty("Id");
await this._container.CreateItemAsync<T>(item,
new PartitionKey(propertyInfo.GetValue(item).ToString()));
}
catch (AggregateException e)
{
Console.WriteLine(e.Message);
}
}
When this runs, the entire calling method fails without exception and returns to the caller. But when I do this from the caller, the code works fine:
using (StreamReader file = File.OpenText(@"Orgs.json"))
{
JsonSerializer serializer = new JsonSerializer();
List<Org> org1 = (List<Org>)serializer.Deserialize(file, typeof(List<Org>));
foreach (var org in org1)
{
orgClient.AddItemAsync(org).Wait();
}
}
(i.e. waiting on the AddItemAsync
method)
I've got the "Just My Code" debugger option disabled. And this is on .NET 5 under VS2022 preview.
Can anyone enlighten me on how I can get this to work properly using the async patterns?