I'm working with an external library that expects me to produce bitmaps when it calls GetImage for the following interface it exposes:
public interface IImageProvider
{
Bitmap GetImage(string imageId);
}
The library asks for them in bulk - i.e. it calls GetImage() repeatedly on the UI thread, thus creating substantial UI lag. Now, I have time to pre-render images for each of these ids before the library actually asks for them. I would like to do so on a background thread, but I am obviously not in a position to return a Task<Bitmap> back through the interface.
What I'm essentially trying to achieve is summmarized below: Let's say I create a library - MySvgLibrary:
public interface MySvgLibrary
{
void Preload();
Dictionary<string, Bitmap> Library { get; }
}
I now want to Task.Run(() => _myLibrary.Preload() }. Given that I don't think I can use async/await here (since I cannot return a Task<Bitmap>, I don't see how I can use, say, a TaskCompletionSource in this context. How do I know that Preload is finished? I mean, I could check if Library is null and spin until it isn't (and that does work, btw) but that approach makes me nauseous. Suggestions?
Taskreturned fromTask.Run()to see if it has finished, usingTask.Wait(0).ConcurrentDictionaryinstead of a normalDictionary? You could have a background process adding rendered images to the dictionary, and on the UI thread just grab the images using theTryGetValuemethod. This class is thread-safe, so no synchronization is needed.