Reputation: 91608
I have the following method:
private async void CreateSchedule(IEnumerable<DateTime> dates)
{
using (var db = new SolverDbContext())
{
foreach (var date in dates)
{
var job = await client.ConfigureJob(new JobConfigurationModel
{
ScheduleDate = date.ToString("yyyy-MM-dd"),
// Bunch of other stuff that doesn't matter
});
var dbSchedule = Schedule.Default;
dbSchedule.Ticket = job;
dbSchedule.ScheduleDate = date;
db.Schedule.Add(dbSchedule);
}
db.SaveChanges();
}
}
Basically it loops through a bunch of dates and calls an awaitable method called ConfigureJob
(Which makes an HTTP call to a web service).
Now, I want to call this method. I've tried:
CreateSchedule(allDates);
This will just no-op and exit immediately. I've also tried:
Task.Run(() => { CreateSchedule(allDates); }).Wait();
This does the same.
It seems I have to make CreateSchedule
return a Task<T>
or enumeration of Tasks to wait on. What's the correct approach here?
Upvotes: 0
Views: 96
Reputation: 38077
Don't use async void
, that is intended for use as in event handlers. Instead you should be returning a Task.
private async Task CreateSchedule(IEnumerable<DateTime> dates)
{
// The rest of your code can remain the same.
}
Then in your consuming code, you should use async semantics all the way up, so you should await that result in a method that returns a Task
:
[TestMethod]
public async Task TestScheduler()
{
// .. Maybe some prep work here ..
await CreateSchedule(allDates);
// .. Do Some Assert Checks Here ..
}
Upvotes: 1