private void UnloadHosts(EnvironmentPool collection)
 {
     foreach (var host in collection.Hosts)
     {
         try
         {
             this.Log().Debug($"Unloading generation host {host.Domain.FriendlyName}");
             AppDomain.Unload(host.Domain);
         }
         catch (Exception /*e*/)
         {
             this.Log().Debug($"Failed to unload generation host {host.Domain.FriendlyName}");
         }
     }
 }
        private string[] GenerateForCollection(EnvironmentPool collection, BuildEnvironment environment)
        {
            (RemoteSourceGeneratorEngine Wrapper, AppDomain Domain)hostEntry = (null, null);

            try
            {
                if (!collection.Hosts.TryTake(out hostEntry))
                {
                    hostEntry = CreateDomain(environment);
                }
                else
                {
                    // Try pinging the remote appdomain, as it may throw a RemotingException exception with this error:
                    // Error : Object '/b612ce25_b538_486d_882a_28a019c782ed/p6lmd0em_mrlqpchbk5gh2mk_10.rem' has been disconnected or does not exist at the server.
                    try
                    {
                        if (hostEntry.Wrapper.Ping())
                        {
                            this.Log().Debug($"Reusing generation host ({collection.Entry.ProjectFile}, {string.Join(", ", collection.Entry.SourceGenerators)})");
                        }
                    }
                    catch (System.Runtime.Remoting.RemotingException /*e*/)
                    {
                        this.Log().Debug($"Discarding disconnected generation host for ({collection.Entry.ProjectFile}, {string.Join(", ", collection.Entry.SourceGenerators)})");

                        hostEntry = CreateDomain(environment);
                    }
                }

                var remotableLogger = new RemotableLogger2(this.Log());

                return(hostEntry.Wrapper.Generate(remotableLogger, environment));
            }
            finally
            {
                if (collection != null)
                {
                    collection.Hosts.Add(hostEntry);
                }
            }
        }
 private static EnvironmentPool GetEnvironmentPool(EnvironmentPoolEntry entry)
 => _domains.TryGetValue(entry, out var hosts)
                         ? hosts
                         : _domains[entry] = new EnvironmentPool(entry);