Question

I am trying to create a simple coin toss game. I am trying to create "spin the coin" effect. I have two BitmapImages which shows coin from little different angle. I have for loop and try to change BitmapImage from Image. This however doesn't work for some reason, it just skips coinflip and shows results. If I put MessageBox between each imagechange, it works. Why?

public void spinCoin()
    {
        for (int i = 0; i < 200; i++)
        {
            try
            {
                imageBox.Source = side1;
                imageBox.Source = side2;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

        }
    }

Whole code can be found here: http://pastebin.com/cS3vZhKN http://pastebin.com/7xNsLgWC

EDIT: Working code:

public async void spinCoin()
    {
        label.Content = "Heitetään...";

        for (int i = 0; i < 5; i++)
        {
            imageBox.Source = side1;
            await Task.Delay(50);
            imageBox.Source = side2;
            await Task.Delay(50);


        }

    }

-

public async void button1_Click(object sender, RoutedEventArgs e)
    {
        spinCoin();
        await Task.Delay(600);
        if (tossCoin() == 1)
        {
            imageBox.Source = kr;
            label.Content = "Kruuna!";
        }
        else
        {
            imageBox.Source = kl;
            label.Content = "Klaava!";
        }
    }
Was it helpful?

Solution

Since this must be executing on the UI thread, the UI never gets a chance to update before the method exits. Even if this was executing in parallel with the UI thread, it would go way too fast for the UI to properly display the animation.

You need a timer mechanism to pace the updates and have it run on a background thread. Alternatively, you could make the method async and insert await Task.Delays between each assignment of the image source.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top