Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# System.InvalidOperationException,对象在别处使用_C#_Multithreading_Exception - Fatal编程技术网

C# System.InvalidOperationException,对象在别处使用

C# System.InvalidOperationException,对象在别处使用,c#,multithreading,exception,C#,Multithreading,Exception,我在随机的时间得到了无效操作异常 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].IsA

我在随机的时间得到了无效操作异常

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();
}
这应该会有所帮助

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);
        }

原因是您正面临交叉线程问题

通常的用法是调用应用程序。运行一次以启动windows消息泵。为什么需要应用程序。运行以被多次调用?你想实现什么?我想,因为它是一个windows窗体,而不仅仅是我调用的一个类,我需要使用Application.Run?我不是说这是不可能的,但如果你有一个应用程序消息泵,你可以通过创建一个并调用show来显示新窗体:var frm=new MyForm;frm.Show;当您试图同时在两个线程上使用位图时,会出现这种异常。当然,你已经为这件事创造了很多机会。您需要查看调用堆栈窗口来猜测此异常发生的位置,它通常发生在没有源代码的.NET Framework代码中。就像控件的OnPaint方法一样。在多个线程上创建UI是一种高级编程技术,有许多令人讨厌的陷阱,实际用途很少。