WebBrowser control get all controls on a thread not working

256 views Asked by At

I have WebBrowser control and i am calling a function to get all the control ID from a thread. the functions works when i called it from the UI thread but does not get any control if called from a separate thread.

I am lost please help

calling:

List<WebOparator.WebOparator.WebControls> wcList = oparator.GetAllControlName();
int tryCount = 0;
do
{

if (wcList.Count == 0)
{
    tryCount++;
    Thread.Sleep(2000);
    wcList = oparator.GetAllControlName();
 }
 if (tryCount >= 5) break;
 } while (wcList.Count == 0);

Method:

    public List<WebControls> GetAllControlName()
    {

            List<WebControls> names = new List<WebControls>();
            if (this.InvokeRequired)
            {

                this.BeginInvoke((MethodInvoker)delegate
                {
                    int i = 0;
                    foreach (HtmlElement element in myBrowser1.Document.All)
                    {
                        if (element.Id != null)
                        {
                            i++;
                            names.Add(new WebControls() { sl = i, ID = element.Id, TagName = element.TagName });
                        }
                    }
                });
            }
            else
            {
                int i = 0;
                foreach (HtmlElement element in myBrowser1.Document.All)
                {
                    if (element.Id != null)
                    {
                        i++;
                        names.Add(new WebControls() { sl = i, ID = element.Id, TagName = element.TagName });
                    }
                }
            }
            return names;


    }

Edit:

I found that the function goes in loops through all the control and add them to the list but returns an empty list....

1

There are 1 answers

0
SLaks On BEST ANSWER

BeginInvoke() is asynchronous.
That delegate yuns on the UI thread after the rest of your code finishes.

You want Invoke(), which will synchronously wait for the delegate to finish running.