Multithreaded BackgroundAgent?

334 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

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.

1
On

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.