C# System.InvalidCastException

后端 未结 2 1265
走了就别回头了
走了就别回头了 2020-12-10 22:09

Why I\'m getting this error?

\"enter

System.InvalidCastException was u         


        
相关标签:
2条回答
  • 2020-12-10 22:46

    The following solves your cross thread issue.

    public delegate string GetStringHandler();
    public string GetDocumentText()
    {
        if (InvokeRequired)
            return Invoke(new GetStringHandler(GetDocumentText)) as string;
        else
            return webBrowser.DocumentText;
    }
    
    if (regAddId.IsMatch(GetDocumentText()))
    {
    }
    
    0 讨论(0)
  • 2020-12-10 22:54

    I get a threading exception with this test:

    public class Test
    {
        private readonly WebBrowser wb;
    
        public Test()
        {
            wb = new WebBrowser();
            var bw = new BackgroundWorker();
            bw.DoWork += DoWork;
            bw.RunWorkerAsync();
    
            while (bw.IsBusy)
            {
                Thread.Sleep(10);
                Application.DoEvents();
            } 
        }
    
        private void DoWork(object sender, DoWorkEventArgs e)
        {
            wb.Navigate(@"www.clix-cents.com/pages/clickads");
            Thread.Sleep(1000);
            var regex = new Regex("onclick=\\'openad\\(\"([\\d\\w]+\"\\);");
            regex.IsMatch(wb.DocumentText);
        }
    }
    
    public class Program
    {
        [STAThread]
        public static void Main(string[] args)
        {
            new Test();
        }
    }
    

    The exception looks like this: Exception

    Since WebBrowser is really just a wrapper around IE's ActiveX control, you'll need to be careful about threading issues. I think what you really want to use here is a WebClient and not a WebBrowser, but I'm just guessing about your application.

    [EDIT]

    Like @Fun states you can just Invoke over to the GUI thread (assuming thats where the control was created. I'd still recommend using a WebClient.

    0 讨论(0)
提交回复
热议问题