Selalu_Ingin_Belajar
Selalu_Ingin_Belajar

Reputation: 375

appdomain close console without kill main process

hi i need direction how to close appdomain console application without kill main process?

i create appdomain like this.

AppDomain testApp = AppDomain.CreateDomain("testApp");
try
{
    string[] args = new string[] { };
    string path = ConfigurationManager.AppSettings.Get("testApp");

    testApp.ExecuteAssembly(path, new System.Security.Policy.Evidence(), args);
}
catch (Exception ex)
{
    //Catch process here
}
finally
{
    AppDomain.Unload(testApp);
}

"testApp" was console application, and when I close that console, main application that call AppDomain closing.

*Edit I execute code above on main application, let's say "MyApplication". When code above executed, its runs "testApp" and console windows show up. My problem is when i close "testApp" console windows, "MyApplication" process is closing.

Upvotes: 0

Views: 910

Answers (1)

aiapatag
aiapatag

Reputation: 3430

It could be that the assembly your AppDomain is calling is ending prematurely (Environment.Exit(1), etc.).

What you can do is to subscribe to the AppDomain's event -- ProcessExit.

namespace _17036954
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain testApp = AppDomain.CreateDomain("testApp");
            try
            {
                args = new string[] { };
                string path = ConfigurationManager.AppSettings.Get("testApp");

                //subscribe to ProcessExit before executing the assembly
                testApp.ProcessExit += (sender, e) =>
                {
                    //do nothing or do anything
                    Console.WriteLine("The appdomain ended");
                    Console.WriteLine("Press any key to end this program");
                    Console.ReadKey();
                };

                testApp.ExecuteAssembly(path);
            }
            catch (Exception ex)
            {
                //Catch process here
            }
            finally
            {
                AppDomain.Unload(testApp);
            }
        }
    }
}

Upvotes: 1

Related Questions