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;
}
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With