So I am having an issue with C# async and await. I have 2 long running functions that I want to call asynchronously onLoad on a Windows Forms Application. I encapsulated them in 2 async functions. One gets the Timezones and the other gets the Aggregates. The issue is the data somehow is colliding. These are the functions:
private async void LoadAggregates()
{
//Load Available Aggregates
Task<CanaryAggregate> caTask = GetAggregatesAsync();
CanaryAggregate ca = await caTask;
Dictionary<string, dynamic> Aggs = ca.aggregates;
foreach (KeyValuePair<string, dynamic> item in Aggs/*PropertyDescriptor pd in TypeDescriptor.GetProperties(ca.aggregates)*/)
{
cbAggregate.Items.Add(item.Key);
}
cbAggregate.SelectedIndex = cbAggregate.FindStringExact(Properties.Settings.Default.Aggregate);
}
private async Task<CanaryAggregate> GetAggregatesAsync()
{
CanaryAggregate ca = null;
await Task.Run(() =>
{
ca = Program.caAPI.getAggregates();
});
return ca;
}
private async void LoadTimeZones()
{
//Load the TimeZones
Task<CanaryTimezone> ctzTask = GetTimezoneAsync();
CanaryTimezone ct = await ctzTask;
for (int i = 0; i < ct.timeZones.Length; i++)
{
ToolStripMenuItem tssmiTimezone = new ToolStripMenuItem();
tssmiTimezone.Text = ct.timeZones[i];
tssmiTimezone.Click += new EventHandler(TimezoneChanged);
tssbTimezone.DropDownItems.Add(tssmiTimezone);
}
}
private async Task<CanaryTimezone> GetTimezoneAsync()
{
CanaryTimezone ct = null;
await Task.Run(() =>
{
ct = Program.caAPI.getTimezones();
});
return ct;
}
Somehow the returned data from GetAggregates is being sent back to the data of GetTimezones. And then GetTimezones is throwing a NullReferenceException on the ct.timeZones.length part. I output the data I am receiving from the Program.caAPI.getTimeZones(), and I am getting the aggregate data in that function. When I don't use async await I am receiving the correct data. I don't know why this is happening at all.