Search code examples
c#winformsobjectdisposedexception

Cannot access a disposed object on Program.cs Main method


I have a WinForm application with two different forms. If the first command line argument is "download", the Download form should appear. I get an ObjectDisposedException on the Application.Run(new Download(args)); line on the Main method of my program.

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        if (args.Length > 0)
            switch (args[0])
            {
                case "download":
                    if (args.Length == 4)
                        Application.Run(new Download(args));
                    break;
                default:
                    Application.Run(new ApsisRunner(args));
                    break;
            }
    }
}

enter image description here

Update: Exception stack trace

   at System.Windows.Forms.Control.CreateHandle()
   at System.Windows.Forms.Form.CreateHandle()
   at System.Windows.Forms.Control.get_Handle()
   at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
   at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
   at System.Windows.Forms.Control.set_Visible(Boolean value)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at ApsisCampaignRunner.Program.Main(String[] args) in c:\Users\pedram.mobedi\Documents\GitHub\Postbag\ApsisCampaignRunner\Program.cs:line 31
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Solution

  • Are you doing something like this one in the Constructor of Download form?

    enter image description here

    The problem might be in code of Download Form. You should not close or dispose Form in the constructor.