user1884304
user1884304

Reputation: 39

Wait for a fixed time before start another method

I want to have a way to wait for a method to complete in 5 seconds before start another call. It was like it first display a "Hello" then wait for 5 seconds, then display "World" and wait for another 5 seconds to display both messages again. I have created a DispatcherTimer method but it display the both text in a fast manner inside of waiting 5 seconds.

    private void AutoAnimationTrigger(Action action, TimeSpan delay)
    {
        timer2 = new DispatcherTimer();
        timer2.Interval = delay;
        timer2.Tag = action;
        timer2.Tick += timer2_Tick;

        timer2.Start();
    }

    private void timer2_Tick(object sender, EventArgs e)
    {
        timer2 = (DispatcherTimer)sender;
        Action action = (Action)timer2.Tag;

        action.Invoke();

        timer2.Stop();
    }


 if (counter == 0)
                {
                    AutoAnimationTrigger(new Action(delegate { MessageBox.Show("Hello"); }), TimeSpan.FromMilliseconds(5000));
                    AutoAnimationTrigger(new Action(delegate { MessageBox.Show("World"); }), TimeSpan.FromMilliseconds(5000));

                }

What do I miss or did wrong?

edit___

 ThreadPool.QueueUserWorkItem(delegate
        {
            //Thread.Sleep(5000);

            Dispatcher.Invoke(new Action(() =>
            {
                TranslateX(4);
                TranslateY(-0.5);

            }), DispatcherPriority.Normal);


            //Dispatcher.BeginInvoke(new Action(() =>
            //{
            //    TranslateY(0.5);
            //}), DispatcherPriority.Normal);

        });

Then i just simply call the method..

Upvotes: 1

Views: 3221

Answers (2)

VladL
VladL

Reputation: 13043

You call AutoAnimationTrigger twice which overwrites timer2, which you declared as a class variable. The easier solution for multiple different actions would be using Thread.Sleep:

 ThreadPool.QueueUserWorkItem(delegate
 {
    Thread.Sleep(5000);
    MessageBox.Show("Hello");
    Thread.Sleep(5000);
    MessageBox.Show("World");
    Thread.Sleep(5000);      
    MessageBox.Show("Hello World");  
 });

Upvotes: 3

Mehbube Arman
Mehbube Arman

Reputation: 490

Just use Thread.Sleep(5000) between two method calling.

Upvotes: 0

Related Questions