[WinPhone]Why is this working, while that isn’t?

I was experimenting with tasks, awaits asyncs and cancellation tokens recently.

I have two snippets of code:


public async static Task SetBackground(string path, Transition transition=Transition.None) { Image newBg = new Image() { Opacity = 0, Stretch = Stretch.UniformToFill, Source = new BitmapImage(new Uri("ms-appx:///" + path)) }; Core.backgroundImage.Children.Add(newBg); switch(transition) { case Transition.None: newBg.Opacity = 1.0; break; case Transition.QuickDissolve: for (int i = 0; i < 20; i++) { newBg.Opacity += 1 / 20f; await Task.Delay(6); } break; ... } 


public async static Task ClearBackground() { Image bg = Core.backgroundImage.Children[0] as Image; //Core is a custom class that has reference to MainPage.xaml's grid backgroundImage for (int i = 0; i < 32; i++) { bg.Opacity -= 1 / 32; await Task.Delay(6); } Core.backgroundImage.Children.Clear(); } 

The first function works fine. It creates new sprite, then, depending on the transition, shows it accordingly.

The second one is more problematic. The app freezes for a second, then the background disappears instantly. No slowly opacity decreasing, it just waits a few seconds then it dies.

Why is that? I was thinking about it I have a theory that it's because in the case of the 2nd function I'm using the reference inherited from a Grid, while in the 1st it's newly instantiated Image. Am I right? Does it even make any sense?

by MrReynevan2 via /r/csharp

Leave a Reply