COMException after Thread.Sleep()

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.

c#
exception
browser
asked on Stack Overflow May 25, 2013 by f0rtis

1 Answer

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:

answered on Stack Overflow May 25, 2013 by Ashraf ElSwify • edited May 23, 2017 by Community

User contributions licensed under CC BY-SA 3.0