In a Xamarin.iOS app, for various reasons we can't use async/await. Therefore, we are using Task.ContinueWith. The problem is that objects we rely on in the continuation are disposed before the continuation gets called.
using (UIImage image = // Somehow get the image)
{
DoSomethingWith(image);
}
void DoSomethingWithImage(UIImage image)
{
UploadImageAsync(image).ContinueWith(t =>
{
// Image has been disposed by this point.
DisplayResult(t.Result, image);
});
}
I'm interested to get ideas on how to manage the above case. Options I've considered:
- Remove the
usingblock, and letimagego out of scope. This would be a bad idea, sinceUIImagecould be quite large. - Remove the
using, and callDispose()in the continuation. This feels error-prone, as whereever code like this exists, you're disposing the object far from where it was created. - Wrap the call to
DoSomethingWithImage()in aTask.Run(() => DoSomethingWithImage(image)).ContinueWith(t => image.Dispose()). So you have a continuation within a continuation. This feels over-complicated for this scenario. - Any other options I'm overlooking?