Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6055145
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T08:13:58+00:00 2026-05-23T08:13:58+00:00

I have a service that loads a child AppDomain and then starts a thread

  • 0

I have a service that loads a child AppDomain and then starts a thread running in it. It needs an AppDomain because it dynamically generates and loads some code and I need to be able to restart it without killing the whole service.

So there is a thread running in an event loop in the child AppDomain, it gets events passed to it through a MarshalByRefObject that sticks stuff in a concurrent queue. I want to stop and unload the child AppDomain and create a new one.

I can simply call Unload on the child AppDomain, but that will abort all the threads and throw a ThrearAbortException. How can I gracefully shut it down? If I set some static flag in the child AppDomain using the MarshalByRefObject then how will the main process be able to wait until its done unloading?

I have some example code that kind of shows how its setup and how I can call Unload to kill it, how could I modify this to allow graceful unloading and never have multiple child AppDomains?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Security.Permissions;
using System.Reflection;
using System.Threading;

namespace TestAppDomains
{
    /// <summary>
    /// Calls to methods magically get transfered to the appdomain it was created in because it derives from MarshalByRefObject
    /// </summary>
    class MarshalProxy : MarshalByRefObject
    {
        public AppDomain GetProxyAppDomain()
        {
            return AppDomain.CurrentDomain;
        }

        public void SayHello()
        {
            Console.WriteLine("MarshalProxy in AD: {0}", AppDomain.CurrentDomain.FriendlyName);
        }

        public void RunLoop()
        {
            try
            {
                while (true)
                {
                    Console.WriteLine("RunLoop {0} in {1}", DateTime.Now.ToLongTimeString(), AppDomain.CurrentDomain.FriendlyName);
                    Thread.Sleep(1000);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("You killed me! {0}", ex);
                Thread.Sleep(200); //just to make sure the unload is really blocking until its done unloading
                // if the sleep is set to 2000 then you will get a CannotUnloadAppDomainException, Error while unloading appdomain. (Exception from HRESULT: 0x80131015) thrown from the .Unload call
            }
        }

        static int creationCount = 1;
        public static MarshalProxy RunInNewthreadAndAppDomain()
        {
            // Create the AppDomain and MarshalByRefObject
            var appDomainSetup = new AppDomainSetup()
            {
                ApplicationName = "Child AD",
                ShadowCopyFiles = "false",
                ApplicationBase = Environment.CurrentDirectory,
            };

            var childAppDomain = AppDomain.CreateDomain(
                "Child AD " + creationCount++,
                null,
                appDomainSetup,
                new PermissionSet(PermissionState.Unrestricted));

            var proxy = (MarshalProxy)childAppDomain.CreateInstanceAndUnwrap(
                typeof(MarshalProxy).Assembly.FullName,
                typeof(MarshalProxy).FullName,
                false,
                BindingFlags.Public | BindingFlags.Instance,
                null,
                new object[] { },
                null,
                null);

            Thread runnerThread = new Thread(proxy.RunLoop);
            runnerThread.Name = "MarshalProxy RunLoop";
            runnerThread.IsBackground = false;
            runnerThread.Start();

            return proxy;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("I am running in AD: {0}", AppDomain.CurrentDomain.FriendlyName);

            var proxy = MarshalProxy.RunInNewthreadAndAppDomain();
            proxy.SayHello();

            while (true)
            {
                Console.WriteLine("Press enter to kill and restart proxy");
                Console.WriteLine();
                Console.ReadLine();

                Console.WriteLine("Unloading");
                AppDomain.Unload(proxy.GetProxyAppDomain());
                Console.WriteLine("Done unloading");

                proxy = MarshalProxy.RunInNewthreadAndAppDomain();
            }
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T08:13:58+00:00Added an answer on May 23, 2026 at 8:13 am

    Try the following

    runnerThread.IsBackground = true;
    

    And, yeah, there is no graceful unloading of AppDomain if you didn’t stop the threads first.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an application that loads core data, then calls the XML Web Service
I have a app that loads some json from my php web service. This
I have a service that loads a dll into a seperate appdomain(the appdomain is
I have a thread that loads data when a service is starting. I call
I have a windows service that loads multiple handlers written by different developers. The
I have a service that I would like it to become single instance, because
I have a service that needs to update the registry every 5 minutes (counteract
I have a windows service that runs and starts up fine, however, it runs
I have a Sencha Touch App that loads data from a REST service into
I have a windows service that loads a bunch of 'plugins' that are just

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.