开发者

WPF control containing an IDisposable member

开发者 https://www.devze.com 2023-01-16 04:09 出处:网络
I have a member in the WPF code behind that is disposable (meaning it implements the IDisposable interface)

I have a member in the WPF code behind that is disposable (meaning it implements the IDisposable interface)

I do not see any Dispose method I can override from UserControl in WPF so I can dispose of the member in my wpf usercontrol

What is the correct way to dispose of a member in a WPF usercontrol?

It's a usercontrol that wraps a private member which implements the IDisposable interface. Thus I need to dispose of that member somewhere. In the tradition winform, the usercontrol had a Dispose method that could be overriden so that in the override I could dispose of the private membe开发者_高级运维r. But in the WPF usercontrol, there is no such thing. So I was wondering where can I dispose of the private member in the wpf usercontrol.

My question is not about disposing the usercontrol, but where to dispose one of its private member which implement the IDisposable interface


You could use the Unloaded event of the UserControl to do your resource cleanup.


You would do it in the Dispatcher.ShutDownStarted event handler. See this question for details (which in turn refers to this blog post).


UPDATE

When you call into your private member that implements IDisposable, can you use using? This way, it gets disposed of automatically. I haven't personally done it this way in a UserControl, but it might do the trick. e.g.

using( MyPrivateDisposable mpd = new MyPrivateDisposable) {
    mpd.MethodA();
}

old answer

If you can't call Dispose(), the problem is that your UserControl doesn't inherit from Disposable(). UserControl itself is not derived from it so you have to explicitly make your WPF control inherit from it, i.e.

public class MyControl : UserControl, IDisposable {...}

See the UserControl base types here:

WPF control containing an IDisposable member

Once you implement IDisposable, you can call it. But as I wrote in my comment to your question, I think you need to post more information about this class. Ask yourself if you really need to call Dispose() on it... i.e. does your UserControl access handles, or use unmanaged code? If not, I don't see why you would have to call Dispose() on it unless you really wanted the GC to clean it up.

0

精彩评论

暂无评论...
验证码 换一张
取 消