Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using AppDomain.DoCallBack() asynchronously

Tags:

c#

appdomain

I am trying to call DoCallBack for multiple AppDomains, but it is not asynchronous. Is there a way to make the calls asynchronous? Here is what I am attempting to do:

        var appDomain1 = System.AppDomain.CreateDomain("event1");
        var appDomain2 = System.AppDomain.CreateDomain("event2");

        Console.WriteLine("Executing appDomain1");
        appDomain1.DoCallBack(new CrossAppDomainDelegate(Event));
        Console.WriteLine("Executing appDomain2");
        appDomain2.DoCallBack(new CrossAppDomainDelegate(Event));

I am attempting to execute the method "Event" in multiple appDomains asynchronously.

like image 770
TheDude Avatar asked Feb 06 '26 01:02

TheDude


2 Answers

You could use the TPL, and call DoCallBack from a Task:

var task1 = Task.Factory.StartNew(() => appDomain1.DoCallBack(Event));
var task2 = Task.Factory.StartNew(() => appDomain2.DoCallBack(Event));
Task.WaitAll(task1, task2);
like image 93
m0sa Avatar answered Feb 08 '26 13:02

m0sa


Although it may suite your needs just fine, DoCallBack is a bit limited. Consider this instead (also works in parallel):

namespace ConsoleApplication1
{
    using System;
    using System.Threading.Tasks;
    using AppDomainToolkit;

    class Program
    {
        static void Main(string[] args)
        {
            using (var context1 = AppDomainContext.Create())
            using (var context2 = AppDomainContext.Create())
            {
                var task1 = Task.Factory.StartNew(
                    () =>
                    {
                        RemoteAction.Invoke(
                            context1.Domain, 
                            () => 
                            {
                                var appName = AppDomain.CurrentDomain.SetupInformation.ApplicationName;
                                Console.WriteLine("Hello from app domain " + appName);
                            });
                    });

                var task2 = Task.Factory.StartNew(
                    () =>
                    {
                        RemoteAction.Invoke(
                            context2.Domain,
                            () =>
                            {
                                var appName = AppDomain.CurrentDomain.SetupInformation.ApplicationName;
                                Console.WriteLine("Hello from app domain " + appName);
                            });
                    });

                // Be sure to wait, else the domains will dispose
                Task.WaitAll(task1, task2);
            }

            Console.ReadKey();
        }
    }
}

More information is available here: https://github.com/jduv/AppDomainToolkit

like image 23
Jduv Avatar answered Feb 08 '26 14:02

Jduv