I know most of you are probably sick and tired of my experiences with Async.
Since i had so much fun with async on Windows Phone and on Windows 8 dev, i decided to use my azure account and to build data repo there. In simple terms, i do this on azure
- Get a list of objects – e.g. film list
- for each film in the above list, query other services for addtional data.
- persist the data.
The implementation i did was simple.. Create a project with Azure services and add WorkerRole to it.
In worker role, use async like we know
AsyncDataSourceObj aeo = new AsyncDataSourceObj();
protected async Task BuildFilmDataSet()
{
Films films = await aeo.GetFilmData();
foreach(var film in films)
{
Cinemas cinemas = await aeo.GetCinemaData(film);
// do things
// do more things
}
}
This doesn’t work as you’d imagine. Within the foreach loop, once await is called, the execution instead of waiting for it to complete, goes to the next iternation of foreach and it fails for some reason.
Now you know how much i love calling Wait() on async.. so what did i do ? well its not a time critical thing i am doing here and i do not mind blocking the thread worker role is running on.
AsyncDataSourceObj aeo = new AsyncDataSourceObj();
protected async Task BuildFilmDataSet()
{
Task<Films> tfilms = aeo.GetFilmData();
tfilms.Wait();
if(!tfilms.IsFaulted && tfilms.Result != null)
{
foreach(var film in tfilms.Result)
{
Task<Cinemas> tcinemas = aeo.GetCinemaData(film);
tcinemas.Wait();
// do things
// do more things
}
}
Now it works as you’d expect. If you ever get stuck in similar situation, you know what to do next!!
Pingback: #async task and the for loop bug | Invoke IT Limited
Using wait is dangerous if you do it more than once in your call tree, as you may block the code that’s being awaited somewhere else.
it depends on what you are doing and as long as you understand what is going on. I wouldn’t advise waiting on UI threads but in background threads or when you don’t mind real sync calls, wait is just fine.