0

I'm writing a BackgroundAgent for my WP7 app that periodically downloads an image from the internet, modifies it, then updates the live tile with it. I've found that loading the bitmap image is asynchronous, and requires registering the ImageOpened event.

sourceBitmap.ImageOpened += new EventHandler<RoutedEventArgs>((sender, e) => ...

The problem is that this brings me off of the main thread, which will return back to the ScheduledAgent and call NotifyComplete() before the new thread has finished. I assume this will cause problems and is not ideal.

Is there a way to have the main thread wait until the image is loaded, edited, and pushed to the live tile?

Or should I just use a field IsComplete and Thread.Sleep() until it is true?

Adam Anderson
  • 339
  • 3
  • 14

2 Answers2

1

Don't call Thread.Sleep.

You just need to carefully manage your calls to NotifyComplete to make sure that you don't cal it before the download is complete.

Matt Lacey
  • 65,560
  • 11
  • 91
  • 143
  • Good point. I now realize that even if the originating thread completed, as long as I don't call `NotifyComplete` before the download/edit is complete, it should be fine (theoretically...haven't tried it). Unfortunately I ran into another unrelated problem that makes me rethink my strategy for this (no `BitmapImage`s on background threads...argh). Thanks anyway! – Adam Anderson Oct 24 '11 at 20:19
0

Use the Task Parallel Library. That way you can add continuations, to force the tasks to wait for your async events, before calling NotifyComplete().

I've written a blog post about it.

Short part is to use a TaskCompletionSource<T>, to make the TPL continuations wait for the ImageOpened event.

Perfectly doable.

TPL for Windows Phone, can be found on NuGet.

Claus Jørgensen
  • 25,882
  • 9
  • 87
  • 150
  • Oh, nice! Sounds similar to what `await` will be in C# 5. Also, I think your blog post solved my other problem with loading a `BitmapImage` in the task. Thanks! – Adam Anderson Oct 25 '11 at 13:57