主AppDomain
只需創建遠程主機的對象,並將其傳遞到新初始化的子域。每當孩子想要向主機發送數據時,使用這個遠程主機對象。
// This class provides callbacks to the host app domain.
// As it is derived from MarshalByRefObject, it will be a remote object
// when passed to the children.
// if children are not allowed to reference the host, create an IHost interface
public class DomainHost : MarshalByRefObject
{
// send a message to the host
public void SendMessage(IChild sender, string message)
{
Console.WriteLine($"Message from child {sender.Name}: {message}");
}
// sends any object to the host. The object must be serializable
public void SendObject(IChild sender, object package)
{
Console.WriteLine($"Package from child {sender.Name}: {package}");
}
// there is no timeout for host
public override object InitializeLifetimeService()
{
return null;
}
}
我懷疑孩子對象,你已經創建實現一個接口,這樣你就可以從主域引用它們無需加載其實際類型。在初始化時,您可以將它們傳遞給主機對象,以便在初始化後可以從子級執行回調。
public interface IChild
{
void Initialize(DomainHost host);
void DoSomeChildishJob();
string Name { get; }
}
ChildExample.dll:
internal class MyChild : MarshalByRefObject, IChild
{
private DomainHost host;
public void Initialize(DomainHost host)
{
// store the remote host here so you will able to use it to send feedbacks
this.host = host;
host.SendMessage(this, "I am being initialized.")
}
public string Name { get { return "Dummy child"; } }
public void DoSomeChildishJob()
{
host.SendMessage(this, "Job started.")
host.SendObject(this, 42);
host.SendMessage(this, "Job finished.")
}
}
用法:
var domain = AppDomain.CreateDomain("ChildDomain");
// use the proper assembly and type name.
// child is a remote object here, ChildExample.dll is not loaded into the main domain
IChild child = domain.CreateInstanceAndUnwrap("ChildExample", "ChildNamespace.MyChild") as IChild;
// pass the host to the child
child.Initialize(new DomainHost());
// now child can send feedbacks
child.DoSomeChildishJob();
感謝米哈爾和taffer! – Abby
這簡化了很多東西! – Abby
@abby - 如果我的回答很有幫助,您可以接受並投票。 –