0

I have program in C# for parse new post on forum. When i parse page without post (post doesn't exist), i use

if (find("Doesn't exist"))
{
     System.Threading.Thread.Sleep(10000);
     button2.PerformClick();
}

Then usually post again doesn't exist and again Thread is sleeping for 10 sec. But after i have COMException with HRESULT: 0x800700AA. How to avoid this exception and what i'm doing wrong? Thanks.

f0rtis
  • 326
  • 2
  • 13
  • what action does the `button2.PerformClick()` perform. i.e. does it make any other call to the COM component. post bit more details here. – Saravanan May 25 '13 at 18:47
  • @saravanan webBrowser1.Stop(); webBrowser1.Url = new Uri(address); – f0rtis May 26 '13 at 08:43
  • Did you read this post: http://stackoverflow.com/questions/2230982/webbrowser-navigate-throws-comexception – Saravanan May 26 '13 at 09:00
  • @saravanan Yes. If i replace `System.Threading.Thread.Sleep(10000); button2.PerformClick();` to `Thread.Sleep(10000); if (webBrowser1.IsBusy) webBrowser1.Stop(); button2.PerformClick();` , then anyway webBrowser1.IsBusy is true. ReadyState in that moment is "Complete". – f0rtis May 26 '13 at 10:24

1 Answers1

0

This COMException indicates that the browser object is busy. This seems to me because putting the current thread into sleep is not a good idea, and your case is detrimental.

I am assuming you are running this in the main UI thread, which is killing your main message pump/queue.

There are numerous solutions to solve this problem, depending on which UI framework you are using, such as Windows Forms, or WPF, etc ...

EveniIf you are using .Net 4.5 or have the luxury to use it, you could also have solutions based on Tasks and Async features introduced there.

Here is the solution I recommend for you, but it is not the only one:

Implement this method:

public static class UICallbackTimer
{
    public static void DelayExecution(TimeSpan delay, Action action)
    {
        System.Threading.Timer timer = null;
        SynchronizationContext context = SynchronizationContext.Current;

        timer = new System.Threading.Timer(
            (ignore) =>
            {
                timer.Dispose();

                context.Post(ignore2 => action(), null);
            }, null, delay, TimeSpan.FromMilliseconds(-1));
    }
}

Then you would call it from you code:

if (find("Doesn't exist"))
{
    UICallbackTimer.DelayExecution(TimeSpan.FromSeconds(10),
        () => button2.PerformClick());     
}

There are plenty of articles on SO that describes various solutions to this issue and I picked the best for you:

Community
  • 1
  • 1
Ashraf ElSwify
  • 192
  • 1
  • 8
  • Thanks, but you're solution didn't help( After second call `DelayExecution()` webbrowser again is busy. – f0rtis May 26 '13 at 10:29