Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.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
.net &引用;无法访问已处置对象“;启动WinForm时出错_.net_Winforms_Automation - Fatal编程技术网

.net &引用;无法访问已处置对象“;启动WinForm时出错

.net &引用;无法访问已处置对象“;启动WinForm时出错,.net,winforms,automation,.net,Winforms,Automation,我有很多应用程序,它们检查命令行中的参数,启动WinForm,然后如果设置了标志,则运行一个进程并关闭表单。因此,我可以在无人监督的情况下运行流程 我注意到其中一些应用程序在无人监督的情况下运行时出现故障,尽管它们的结构与其他十几个应用程序相同,并且在我手动运行时运行良好 要重新创建问题,请执行以下操作: static void Main() { bool _unsupervised = ParseCommandLine(); Application.Run(new F

我有很多应用程序,它们检查命令行中的参数,启动WinForm,然后如果设置了标志,则运行一个进程并关闭表单。因此,我可以在无人监督的情况下运行流程

我注意到其中一些应用程序在无人监督的情况下运行时出现故障,尽管它们的结构与其他十几个应用程序相同,并且在我手动运行时运行良好

要重新创建问题,请执行以下操作:

static void Main()
    {
    bool  _unsupervised = ParseCommandLine();
    Application.Run(new FormUI(_unsupervised));
    }

class FormUI: Form
    {
    public FormUI(bool unsupervised)
        {
        _unsupervised = unsupervised;
        if (_unsupervised)  Start();
        }
    public void  Start()
        {
        // Do stuff
        if (_unsupervised)  Close();
        }
    private bool  _unsupervised;
    }
结果:
Application.Run()
抛出
ObjectDisposedException
:“无法访问已处置的对象”


类似:

这些有问题的应用程序与其他应用程序之间的区别在于我是将
Start()
(因此,将
Close()
的代码路径)放在构造函数还是
Load()
方法中。通过执行前者,表单在应用程序可以使用
Application.Run()
启动它之前就创建和处理了自己

关键是将此操作移动到构造函数完成后的某个点,例如
OnLoad
事件。这一调整起到了关键作用:

static void Main()
    {
    bool  _unsupervised = ParseCommandLine();
    Application.Run(new FormUI(_unsupervised));
    }

class FormUI: Form
    {
    public FormUI(bool unsupervised)
        {
        this.Load += new System.EventHandler(this.FormUI_Load);
        _unsupervised = unsupervised;
        }
    public void  Start()
        {
        // Do stuff
        if (_unsupervised)  Close();
        }
    private bool  _unsupervised;

    private void  FormUI_Load(object sender, EventArgs args)
        {
        // Key change
        if (_unsupervised)  Start();
        }
    }
现在,
Start()。。Close()
路径仅在表单完全创建后出现