How to dispose objects having asynchronous methods called?

后端 未结 7 2161
再見小時候
再見小時候 2020-12-18 21:34

I have this object PreloadClient which implements IDisposable, I want to dispose it, but after the asynchronous methods finish their call... which

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-18 22:24

    If there are event handlers being registered, you can't really dispose the object while there are events that could be called on it. Your best bet is to make the containing class disposable & store the client in a class variable, to be disposed when the containing class is.

    Something like

    class ContainingClass : IDisposable
    {
        private PreloadClient m_Client;
    
        private void Preload(SlideHandler slide)
        {
             m_Client = new PreloadClient())
    
             m_Client.PreloadCompleted += client_PreloadCompleted;
             m_Client.Preload(slide);
    
        }
        private void client_PreloadCompleted(object sender, SlidePreloadCompletedEventArgs e)
        {
        }
    
        public void Dispose()
        {
            if (m_Client != null)
                m_Client.Dispose();
        }
    }
    

提交回复
热议问题