错误:在创建窗口句柄之前,无法在控件上调用Invoke或BeginInvoke

时间:2012-02-09 07:41:02

标签: c# c#-4.0

首先,我要说我已经讨论了这个问题已经有两天了:尝试了各种替代方案,并从类似问题的网站上阅读了大量问题。

首先让我粘贴我的代码,以便全面了解。

编辑:根据论坛成员的要求,删除了一些可能对问题不必要的代码。

表单1.cs

namespace TestApp
{

public partial class Form1 : Form    
{
    //global declarations
    private static Form1 myForm;
    public static Form1 MyForm
    {
        get
        {
            return myForm;
        }
    }       
    List<DataSet> DataSets = new List<DataSet>();
    int typeOfDataset = 0;
    //delegate for background thread to communicate with the UI thread _
    //and update the metadata autodetection progress bar
    public delegate void UpdateProgressBar(int updateProgress);
    public UpdateProgressBar myDelegate;


    //***************************
    //****  Form Events  ********
    //***************************

    public Form1()
    {
       InitializeComponent();
       if (myForm == null)
       {
           myForm = this;
       }
       DataSets.Add(new DSVDataSet());
       DataSets[typeOfDataset].BWorker = new BackgroundWorker();
       DataSets[typeOfDataset].BWorker.WorkerSupportsCancellation = true;
       myDelegate = new UpdateProgressBar(UpdateProgressBarMethod);
     }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        //e.Cancel = true;
        if (DataSets[typeOfDataset].BWorker != null || DataSets[typeOfDataset].BWorker.IsBusy)
        {
            Thread.Sleep(1000);
            DataSets[typeOfDataset].BWorker.CancelAsync();
        }
        Application.Exit();
    }

    //***************************
    //***  Menu Items Events  ***
    //***************************

    private void cSVToolStripMenuItem_Click(object sender, EventArgs e)
    {
        LoadFillDSVData(',');
    }

    //***************************
    //*** DataGridViews Events **
    //***************************

    private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
    {
        using (SolidBrush b = new SolidBrush(this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
        {
            e.Graphics.DrawString(e.RowIndex.ToString(System.Globalization.CultureInfo.CurrentUICulture), this.dataGridView1.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
        }
        int rowHeaderWidth = TextRenderer.MeasureText(e.RowIndex.ToString(), dataGridView1.Font).Width;
        if (rowHeaderWidth + 22 > dataGridView1.RowHeadersWidth)
        {
            dataGridView1.RowHeadersWidth = rowHeaderWidth + 22;
        }
    }

    private void dataGridView2_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
    {
        using (SolidBrush b = new SolidBrush(this.dataGridView2.RowHeadersDefaultCellStyle.ForeColor))
        {
            e.Graphics.DrawString(e.RowIndex.ToString(System.Globalization.CultureInfo.CurrentUICulture), this.dataGridView2.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
        }
        int rowHeaderWidth = TextRenderer.MeasureText(e.RowIndex.ToString(), dataGridView2.Font).Width;
        if (rowHeaderWidth + 22 > dataGridView2.RowHeadersWidth)
        {
            dataGridView2.RowHeadersWidth = rowHeaderWidth + 22;
        }
    }

    //***************************
    //****** Other Methods ******
    //***************************

    private void LoadFillDSVData(char delimiter)
    {
        //load file through openFileDialog
        //some more openFileDialog code removed for simplicity
        if (DataSets[typeOfDataset].BWorker != null || DataSets[typeOfDataset].BWorker.IsBusy)
        {
            Thread.Sleep(1000);
            DataSets[typeOfDataset].BWorker.CancelAsync();
            DataSets[typeOfDataset].BWorker.Dispose();
        }
        //if file was loaded, instantiate the class
        //and populate it 
        dataGridView1.Rows.Clear();
        dataGridView2.Rows.Clear();
        typeOfDataset = 0;
        DataSets[typeOfDataset] = new DSVDataSet();
        DataSets[typeOfDataset].DataGrid = this.dataGridView1;
        DataSets[typeOfDataset].BWorker = new BackgroundWorker();
        DataSets[typeOfDataset].InputFile = openFileDialog1.FileName;
        DataSets[typeOfDataset].FileName = Path.GetFileName(DataSets[typeOfDataset].InputFile);
        DataSets[typeOfDataset].InputPath = Path.GetDirectoryName(DataSets[typeOfDataset].InputFile);
        DataSets[typeOfDataset].Delimiter = delimiter;
        //read file to get number of objects and attributes
        DataSets[typeOfDataset].LoadFile(DataSets[typeOfDataset].InputFile, DataSets[typeOfDataset].Delimiter);
        //ask to autodetect metadata
        DialogResult dr = MessageBox.Show("Auto detect attributes?", "TestApp", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        switch (dr)
        {
            case DialogResult.Yes:
                toolStripStatusLabel1.Text = "Autodetecting attributes...";
                toolStripProgressBar1.Value = 0;
                toolStripProgressBar1.Maximum = 100;
                toolStripProgressBar1.Style = ProgressBarStyle.Continuous;
                DataSets[typeOfDataset].AutoDetectMetadata(DataSets[typeOfDataset].Attributes);
                break;
            case DialogResult.No: 
                break;
            default: 
                break;
        }
    }

    public void UpdateProgressBarMethod(int progress)
    {
        if (progress > 99)
        {
            toolStripProgressBar1.Value = progress;
            toolStripStatusLabel1.Text = "Done.";
        }
        else
        {
            toolStripProgressBar1.Value = progress;
        }
    } 

}

}

还有一节课:

DSVDataSet.cs

namespace TestApp
{

public class DSVDataSet : DataSet
{
    static Form1 myForm = Form1.MyForm;
    //constructor(s)
    public DSVDataSet()
    {           
        InputType = DataSetType.DSV;
    }


    //autodetects metadata from the file if
    //the user wishes to do so
    public override void AutoDetectMetadata(List<Attribute> attributeList)
    {
        BWorker.WorkerReportsProgress = true;
        BWorker.WorkerSupportsCancellation = true;
        BWorker.DoWork += worker_DoWork;
        BWorker.ProgressChanged += worker_ProgressChanged;
        BWorker.RunWorkerCompleted += worker_RunWorkerCompleted;

        //send this to another thread as it is computationally intensive
        BWorker.RunWorkerAsync(attributeList);
    }

    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        List<Attribute> attributeList = (List<Attribute>)e.Argument;
        using (StreamReader sr = new StreamReader(InputFile))
        {
            for (int i = 0; i < NumberOfAttributes; i++)
            {
                Attribute a = new Attribute();
                attributeList.Add(a);
            }
            for (int i = 0; i < NumberOfObjects; i++)
            {
                string[] DSVLine = sr.ReadLine().Split(Delimiter);
                int hoistedCount = DSVLine.Count();
                string str = string.Empty;
                for (int j = 0; j < hoistedCount; j++)
                {
                    bool newValue = true;
                    str = DSVLine[j];
                    for (int k = 0; k < attributeList[j].Categories.Count; k++)
                    {
                        if (str == attributeList[j].Categories[k])
                        {
                            newValue = false;
                        }
                    }
                    if (newValue == true)
                    {
                        attributeList[j].Categories.Add(str);
                        //removed some code for simplicity
                    }
                }
                int currentProgress = (int)((i * 100) / NumberOfObjects);
                if (BWorker.CancellationPending)
                {
                    Thread.Sleep(1000);
                    e.Cancel = true;
                    return;
                }
                BWorker.ReportProgress(currentProgress); //report progress
            }
        }          
        e.Result = 100; //final result (100%)     
    }

    private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        int update = e.ProgressPercentage;
        myForm.BeginInvoke(myForm.myDelegate, update);
    }

    private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {               

        if (e.Error != null)
        {
            return;
        }
        if (e.Cancelled)
        {
            return;
        }
        else
        {
            int update = (int)e.Result;
            myForm.Invoke(myForm.myDelegate, update);
            for (int i = 0; i < Attributes.Count; i++)
            {
                DataGridViewRow item = new DataGridViewRow();
                item.CreateCells(DataGrid);
                item.Cells[0].Value = Attributes[i].Name;
                switch (Attributes[i].Type)
                {
                    case AttributeType.Categorical:
                        item.Cells[1].Value = "Categorical";
                        break;
                    //removed some cases for simplicity
                    default:
                        item.Cells[1].Value = "Categorical";
                        break;
                }
                item.Cells[2].Value = Attributes[i].Convert;
                DataGrid.Rows.Add(item);
            }
            BWorker.Dispose();
        }
    }
}

}

长话短说,我在DSVDataset.cs中有一个backGroundWorker执行一些“繁重的计算”,因此UI不会冻结(对此新),我使用委托让后台线程与UI通信线程更新一些进度条值。如果用户决定创建一个新的DSVDataSet(通过cSVToolStripMenuItem_Click或tSVToolStripMenuItem_Click),那么我已经添加了一些ifs,无论我在哪里找到合适的,检查是否已经运行了backGroundWorker:如果有,请调用CancelAsync,以便它停止它正在做的任何事情然后。弃用它。 现在,有时当我尝试退出Form1而backGroundWorker可能正在运行时(检查例如Form1_FormClosing),我得到了这篇文章标题中的错误。错误将我带到了DSVDataSet.cs中的这段代码:

    private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        int update = e.ProgressPercentage;
        myForm.BeginInvoke(myForm.myDelegate, update);
    }

按F10将我带到Program1.cs:

   Application.Run(new Form1());

基于我读过的另一个stackoverflow帖子(http://stackoverflow.com/questions/513131/c-sharp-compile-error-invoke-or-begininvoke-cannot-be-called-on-a-control-unti ,看看答案),我通过公开Main类本身的实例来实现该逻辑,因此它总是指向main的这个实例。 所以在Form1.cs中:

private static Form1 myForm;
    public static Form1 MyForm
    {
        get
        {
            return myForm;
        }
    }       
 public Form1()
    {
       InitializeComponent();
       if (myForm == null)
       {
           myForm = this;
       }
     }

在DSVDataset.cs中:

  static Form1 myForm = Form1.MyForm;

我在任何需要的地方使用myForm。

尽管如此,我无法解决这个错误,所以我只能假设我没有正确实现该解决方案,或者我在处理backGroundWorkers方面做错了。 任何帮助将不胜感激,我尽力做到尽可能详细(希望这不是一个矫枉过正的事):

此致

3 个答案:

答案 0 :(得分:3)

代码太多,无法理解所有这些代码。但是当你关闭表单时,后台工作人员似乎仍在工作,因此,后台工作人员的进度更改会使程序崩溃。

对于快速解决方案,请在进度更改时检查表单状态,因为我对winform没有太多经验,但必须有一种方法来检查表单是关闭还是处理。

这不建议,因为它会耦合UI和逻辑。

答案 1 :(得分:3)

正如dBear所说,你的后台工作人员可能会在你的表格处理完毕后仍在解决进度改变事件。阻止表单关闭直到后台工作程序完成,或者在关闭表单之前终止后台工作程序是个好主意。无论您选择哪种选项,最好使用事件进行此类通信。将以下事件定义添加到DSVDataSet,并修改进度更改事件处理程序:

public event ProgressChangedEventHandler ProgressChanged;

private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    if (ProgressChanged != null) {
        ProgressChanged(this, e);
    }
}

完成后,您需要在Form1中进行更改,以便在创建DSVDataSet的新实例后添加事件处理程序:

dsv.ProgressChanged += new ProgressChangedEventHandler(dsv_ProgressChanged);

将您需要的任何代码显示在dsv_ProgressChanged的正文中,例如:

void dsv_ProgressChanged(object sender, ProgressChangedEventArgs e) {
     myForm.Invoke(myForm.myDelegate, update);
}

答案 2 :(得分:2)

首先,看起来好像是在尝试创建Form1的单例实例。最好的方法是使用静态方法,属性或变量创建一个私有构造函数,以创建表单的新实例:

public class Form1 : Form
{
    private static Form1 instance;
    public static Form1 Instance
    {
        get 
        { 
           if(instance == null) { instance = new Form1(); }
           return instance;
        }
    }

    private Form1()
    {
        ......
    }
}

然后改变:

    Application.Run(new Form1());

要:

    Application.Run(Form1.Instance);

然后,您可以在任何其他类中使用Form1.Instance来访问主窗口。 现在,窗口句柄错误通常与未在主线程上创建的表单(Form1)相关联。

按照我提供的模式可以解决您的问题。