I'm creating an application which works with a new AppDomain that can be created and unloaded. I'd like to handle the DomainUnload event so I need to subscribe to it. I can't subscribe to this event from the new AppDomain that can be unloaded as all members from there will not be accessible once the domain is unloaded.
But when I try to subscribe to this event from Main AppDomain I always getting the exception: " System.Runtime.Serialization.SerializationException: Type 'MyNamespace.MainWindow' in assembly 'MyMainAssembly' is not marked as serializable. "
Initially I tried to add an attribute [Serializable] to class in the main app domain, but it didn't help. Then I created a new class 'RemoteHandlerClass' derived from MarshalByRefObject and put the subscription code in it, but I'm also getting the same error. Using the [Serializable] attribute in this class also didn't help. To access members from this class I use proxy object in main app domain created by:
var remoteHandler = (RemoteHandlerClass)workerDomain.CreateInstanceAndUnwrap(
typeof(RemoteHandlerClass).Assembly.FullName, typeof(RemoteHandlerClass).FullName);
How can I subscribe to this event? Preferably I would like to subscribe to this event from the main app domain. The code below can reproduce my issue.
Thanks!
public partial class MainWindow : Window
{
private void Button_Click(object sender, RoutedEventArgs e)
{
var newDomain = AppDomain.CreateDomain("New domain");
newDomain.DomainUnload += UnloadHandler; // System.Runtime.Serialization.SerializationException:
// Type 'MyNamespace.MainWindow' in assembly 'MyMainAssembly'
// is not marked as serializable.
}
private void UnloadHandler(object sender, EventArgs e)
{
}
}
So, when dealing with AppDomains, your handler object needs to be MarshalByRefObject
which its not -- it's just a Window type. Wrap what you are doing in a simple class such as
class DomainContainer : MarshalByRefObject
{
public void StartDomain()
{
var newDomain = AppDomain.CreateDomain("New domain");
newDomain.DomainUnload += UnloadHandler;
}
private void UnloadHandler(object sender, EventArgs e)
{
}
}
and call that in your app.
private void Button_Click(object sender, RoutedEventArgs e)
{
var d = new DomainContainer();
d.StartDomain();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.