Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I wait to Timer finish and then return from function?

Tags:

browser

c#

timer

I want to wait to a timer finish and then return from a function. I tried this:

while(timer1.Enabled)
{
    Application.DoEvents();
}
return value;

But it didn't work and the function returned before the timer really finished. Here's the full function:

System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
int[] foo()
{

    do_something1();

    int[] some_value;

    timer1.Interval = 1000;
    timer1.Tick += new EventHandler(delegate(object o, EventArgs ea)
    {
        if (browser.ReadyState == WebBrowserReadyState.Complete)
        {
            timer1.Stop();
            baa(some_value);
        }
    });
    timer1.Start();

    while (timer1.Enabled)
    {
        Application.DoEvents();
    }

    return some_value;
}
like image 250
Jack Avatar asked Nov 11 '14 21:11

Jack


2 Answers

I think what you actually want is to wait until the browser is ready. If so you can use a loop like this, and instead of Application.DoEvents() I recommend using async/await feature:

while(browser.ReadyState != WebBrowserReadyState.Complete)
{ 
   // you need to make your method async in order to use await
   await Task.Delay(1000);
}
// do your job

Or better you can handle DocumentCompleted event of WebBrowser.

like image 81
Selman Genç Avatar answered Nov 14 '22 21:11

Selman Genç


You can use a Thread instead of a Timer. Launch your waiting method in a Thread and simply wait it to finish with thread.IsAlive.

Your code must look like this:

int[] some_value;

int intervalle = 1000;
Thread thread = new Thread(new ThreadStart(delegate()
{
    while (true)
    {
        Thread.Sleep(intervalle);
        if (browser.ReadyState == WebBrowserReadyState.Complete)
        {
            baa(some_value);
            return;
        }
    }                
}));
thread.Start();

while (thread.IsAlive)
{
    Application.DoEvents();
}

return some_value;
like image 29
Ludovic Feltz Avatar answered Nov 14 '22 23:11

Ludovic Feltz