How do I pass CancellationToken across AppDomain boundary?

后端 未结 2 1305
刺人心
刺人心 2021-02-02 16:04

I have a command object, doing work based on a request from a request queue. This particular command will execute its work in a child appdomain. Part of doing its work in the ch

2条回答
  •  野的像风
    2021-02-02 16:43

    There is actually a much easier way to overcome this obstacle assuming your proxy type is a single responsibility. I am assuming of course that you maintain a collection of your created domains and unload them should your application be closed or your containing object be disposed. I also assume the reason you need the cancellation token is to cancel some async operation in your marshaled reference type. You simply need to do the following:

    Create your tokenSource and token fields and initialize them in your constructor.

    _cancellationTokenSource = new CancellationTokenSource();
    _token = _cancellationTokenSource.Token;
    

    Subscribe to the following events. The UnhandledException will serve the purpose of catching any faulting exception which causes your domain to close prematurely. This should be a best practice.

    var currDomain = AppDomain.CurrentDomain;
                currDomain.DomainUnload += currDomain_DomainUnload;
                currDomain.UnhandledException += currDomain_UnhandledException;
    

    Call cancel on your token source when the domain unload event is called. Additionally you may want to have a dispose method that unsubscribes to the domain events that gets called from either or just let the domain cleanup process garbage collection.

    void currDomain_DomainUnload(object sender, EventArgs e)
        {
            _log.Debug(FormatLogMessage(_identity, "Domain unloading Event!"));
            _cancellationTokenSource.Cancel();
            _logPlayer.Dispose();
        }
    
     void currDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            _log.Error(string.Format("***APP Domain UHE*** Error:{0}", e.ExceptionObject);
            _cancellationTokenSource.Cancel();
            _logPlayer.Dispose();
        }
    

提交回复
热议问题