我正在尝试为多个AppDomain调用DoCallBack,但它不是异步的。有没有办法使调用异步?这是我试图做的事情:
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));
我正在尝试异步执行多个appDomains中的“Event”方法。
答案 0 :(得分:3)
您可以使用TPL,并从任务中调用DoCallBack:
var task1 = Task.Factory.StartNew(() => appDomain1.DoCallBack(Event));
var task2 = Task.Factory.StartNew(() => appDomain2.DoCallBack(Event));
Task.WaitAll(task1, task2);
答案 1 :(得分:3)
虽然它可以很好地满足您的需求,但DoCallBack有点受限。请考虑这一点(也可以并行工作):
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();
}
}
}
此处提供了更多信息:https://github.com/jduv/AppDomainToolkit
答案 2 :(得分:2)
用任何通用异步执行机制包裹跨域调用它,并可能等到所有调用完成。 E.g。
Parallel.ForEach(appDomains, domain => domain.DoCallBack(new CrossAppDomainDelegate(Event)));
或
var countDown = new CountdownEvent();
countDown.AddCount();
foreach (var domain in appdomains)
{
countDown.AddCount();
ThreadPool.QueueUserWorkItem(_ =>
{
domain.DoCallBack(new CrossAppDomainDelegate(Event));
countDown.Signal();
});
}
countDown.Signal();
countDown.Wait();