cnd
cnd

Reputation: 33714

Is there the simple way to wait (some time) without application freeze?

For now I've got

    if blocker then 
        Thread.Sleep(5000)
        do something

It's running in the while circle so my whole application is just being freeze. It's also matters for me to do something in Main application thread so that's why I don't create new.

I think that I need to create temporary Timer, add on elapsed event, handle it and then do something but I just want to know if there is some simple solution for it and I don't need to "re-invent a bicycle"?

Upvotes: 1

Views: 169

Answers (3)

Mare Infinitus
Mare Infinitus

Reputation: 8162

You do not have to reinvent the wheel:

// create a timer that waits 10 seconds and start it
Timer timer = new Timer(10 * 1000);
timer.Elapsed += this.TimerElapsed;
timer.Start(); 

public void TimerElapsed(object o, ElapsedEventArgs args)
{
    MessageBox.Show("Timer has elapsed");  
}

Upvotes: 1

Morten Holmgaard
Morten Holmgaard

Reputation: 7796

I would do something like this:

    private static Timer _timer;

    static void Main(string[] args)
    {
        _timer = new Timer();
        _timer.Elapsed += TimeEvent;
        _timer.Interval = 5000; 
        _timer.Start(); 

        while (Console.Read() != 'q')
        {
            ;     
        }
    }

    public static void TimeEvent(object source, ElapsedEventArgs e)
    {
        Console.Write("Time event!");
        _timer.Stop();
    }

Upvotes: 2

Ammar Bukhari
Ammar Bukhari

Reputation: 2122

You can make a class to which you can pass your problem. And call its method through a thread. and in that class you can make events, so when the class finishes its job, it will raise an event and your app will know that the job is done.

Upvotes: 0

Related Questions