Search code examples
c#xamlwindows-phone-7.1sleepthread-sleep

How to make a function to wait for a specific time in Windows phone?


I am building a Windows phone application with lots of animations. What I need is that when the application starts, it should be done finishing the first animation, say myS() is the name of the storyboard. Only after it is done with the animation, a textblock should appear after 3 seconds. What methods should I use to make the display of textbox wait for the Storyboard to finish? What I tried is using Thread.Sleeps(10000) but that doesn't work. This is the code -

public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        c1.Visibility = Visibility.Collapsed; //c1 is the name of the textbox
        myS.Begin();
        canDisp();
    }

    private void e1_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
    {
        myS1.Begin();
    }

    private void e1_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
    {
        myS2.Begin();
    }
    void canDisp()
    {
        c1.Visibility = Visibility.Visible;
    }}

After the myS.Begin() is done executing, I want the program to wait for 3 seconds & then execute the canDisp() method, how can I achieve that?


Solution

  • If your animation is a Storyboard then it has a Completed event (MSDN link) for just this purpose.

    Your call to Thread.Sleep() was probably being run on the same thread as the animation and so was stopping the animation from running while it was sleeping.
    If you really want to go down this route then you'll need to move your sleep call to a different thread.


    If you really want to use threads, a simple way to do it is:

    System.Threading.ThreadPool.QueueUserWorkItem(obj =>
        {
            System.Threading.Thread.Sleep(5000);
    
            Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("after delay");
                });
        });