System.InvalidOperationException,其他地方使用的对象

时间:2014-01-18 12:58:16

标签: c# multithreading exception

我随机收到InvalidOperationException。

public void abStart()
{ 
    try
    {
        AB ab = new AB(wb.getCookies(), side);
        Application.Run(ab); //this is where the exception is thrown
    }
    catch {  }
}

此方法在不同的线程上执行,如下所示:

if (abON[0] == null || !abON[0].IsAlive)
{
    abON[0] = new Thread(new ThreadStart(abStart));
    abON[0].SetApartmentState(ApartmentState.STA);
    abON[0].Start();
}

1 个答案:

答案 0 :(得分:0)

这应该有帮助

public void abStart()
    {
        try
        {
            AB ab = new AB(wb.getCookies(), side);
            this.Invoke((MethodInvoker)delegate
            {
            Application.Run(ab); //this is where the exception is thrown
            });
        }
        catch { }
    }

这段代码改进了这个:

        try
        {
            this.Invoke((MethodInvoker)delegate
            {
                // handles the code on its own thread
                if (abON[0] == null || !abON[0].IsAlive)
                {
                    abON[0] = new Thread(new ThreadStart(abStart));
                    abON[0].SetApartmentState(ApartmentState.STA);
                    abON[0].Start();
                }
            });
        }
        catch (Exception ex)
        {
            MessageBox.Show("" + ex);
        }

原因是您正面临跨线程