简体   繁体   中英

Unloading AppDomain within not ThreadPool thread

I have System.Threading.Timer callback DoApplicationsToWorkSupervising . So it works pretty well on ThreadPool thread. What I actually need is executing application not only in separate domain but rather in STA thread to run WPF application. Sadly, uncommented variant doesn't allow me to Unload my child appDomain , corresponding thread just blocked at this line (and I have not aborted thread with not unloaded domain).

I tried MTA thread with executing console application, tried set background to false, tried to play with context on thread... same result

Could somebody explain me what I do wrong or suggest proper solution?

public void DoApplicationsToWorkSupervising(object obj)
{
    Application applicationToWork = (Application)obj;
    //var staThread = new Thread(() =>
    //{
        var appDomainSetup = new AppDomainSetup
        {
            ApplicationName = applicationToWork.FileName,
            ApplicationBase = applicationToWork.WorkingDirectory,
            ConfigurationFile = applicationToWork.FileName + ".config"
        };
        var appDomain = AppDomain.CreateDomain(
            applicationToWork.ProcessName,
            null,
            appDomainSetup);
        try 
        {
            int exitCode = appDomain.ExecuteAssembly(
                Path.Combine(applicationToWork.WorkingDirectory,    
                    applicationToWork.FileName),
                new[] {applicationToWork.Arguments});
            logger.LogInfoLow(applicationToWork.FileName + 
                " exited with code " + exitCode);
        }
        catch (Exception ex)
        {
            logger.LogErrorLow("Unhandled exception in " +      
                applicationToWork.FileName);
            logger.LogErrorMedium("Unhandled exception in " + 
                applicationToWork.FileName, ex);
        }
        finally
        {
            AppDomain.Unload(appDomain); //My problem 
        }
    //});
    //staThread.Priority = ThreadPriority.AboveNormal;
    //staThread.SetApartmentState(ApartmentState.STA);
    //staThread.Name = applicationToWork.ProcessName;
    //staThread.IsBackground = true;
    //staThread.Start();
}

After all executions my staThread wasn't alive , but had Stopped and WaitSleepJoin flags. I still don't understand the details, but this post was helpful for me https://stackoverflow.com/a/5949823/2987062

All my application use COM calls and my host application main thread was marked as STAThread. After changing main thread in host to MTAThread the problem disappeared.

I will appreciate for further explanation of this situation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM