本文介绍了在C#中使用网络浏览器和线程时出现InvalidCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在backgroundWorker.DoWork函数中使用webBrowser组件时,出现此异常:

when i trying to use webBrowser component inside the backgroundWorker.DoWork function , i got this exception :

System.InvalidCastException未通过用户代码处理

System.InvalidCastException was unhandled by user code

http://i.stack.imgur.com/EJFT3.jpg

这是我的代码:

void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        //NOTE : Never play with the UI thread here...
        string line;

        //time consuming operation
        while ((line=sr.ReadLine()) != null ){

            int index = line.IndexOf(":");
            HtmlDocument doc = web.Document;
            Thread.Sleep(1000);
            m_oWorker.ReportProgress(cnt);

            //If cancel button was pressed while the execution is in progress
            //Change the state from cancellation ---> cancel'ed
            if (m_oWorker.CancellationPending)
            {
                e.Cancel = true;
                m_oWorker.ReportProgress(0);
                return;
            }

            cnt++;
        }

        //Report 100% completion on operation completed
        m_oWorker.ReportProgress(100);
    }

还是他们在c#中使用线程的另一种方式?

or is their another way to use thread in c# ?

因为当我在主界面中使用Thread.sleep方法时,gui冻结了!!

cause when i use Thread.sleep method in the main the gui freezes !!

推荐答案

WebBrowser不喜欢从其他线程访问.尝试像这样将其传递给RunWorkerAsync():

The WebBrowser doesn't like being accessed from other threads. Try passing it in to RunWorkerAsync() like this:

    private void button1_Click(object sender, EventArgs e)
    {
        HtmlDocument doc = web.Document;
        m_oWorker.RunWorkerAsync(doc);
    }

    void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        HtmlDocument doc = (HtmlDocument)e.Argument;

        //NOTE : Never play with the UI thread here...
        string line;

        //time consuming operation
        while ((line = sr.ReadLine()) != null)
        {
            int index = line.IndexOf(":");

            Thread.Sleep(1000);
            m_oWorker.ReportProgress(cnt);

            //If cancel button was pressed while the execution is in progress
            //Change the state from cancellation ---> cancel'ed
            if (m_oWorker.CancellationPending)
            {
                e.Cancel = true;
                m_oWorker.ReportProgress(0);
                return;
            }

            cnt++;
        }

        //Report 100% completion on operation completed
        m_oWorker.ReportProgress(100);
    }

这篇关于在C#中使用网络浏览器和线程时出现InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 06:13