简体   繁体   English

WPF用户控件清理

[英]wpf user control clean up

I have an application coded using WPF and UserControl. 我有一个使用WPF和UserControl编码的应用程序。 I have linked a parent window together with the user control tabs which are loaded when the program starts-up. 我已经将一个父窗口与用户控制选项卡链接在一起,这些选项在程序启动时会加载。

From there I am able to select a tab which will open the corresponding UserControl. 从那里,我可以选择一个选项卡,它将打开相应的UserControl。 Some UserControls have background workers with threads some are purely used for data capturing and others for data output or generating reports. 有些UserControl的后台工作程序带有线程,有些纯粹用于数据捕获,有些则用于数据输出或生成报告。 When each tab is closed using a class created by us called ClossableItems which allows you to select the close button as well as displaying the tab on our MainWindow. 当使用我们创建的名为ClossableItems的类关闭每个选项卡时,您可以选择关闭按钮以及在我们的MainWindow中显示该选项卡。

The problem that we are encountering is that when the UserControl is closed none of the resources are released back to the system aka. 我们遇到的问题是,当关闭UserControl时,也没有任何资源被释放回系统。 the background worker and the resources needed to display the UserControl. 后台工作人员以及显示UserControl所需的资源。 I have googled ways to force close my UserControl's but to no avail. 我用谷歌搜索的方法来强制关闭我的UserControl,但无济于事。 Things I have tried : 我尝试过的事情:

Background worker:
bwDataCollector.WorkerSupportsCancellation = true;
bwDataCollector.CancellationPending;
bwDataCollector.CancelAsync();


User Control:
this.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted
private void Dispatcher_ShutdownStarted(object sender, EventArgs e)
        {
        }

So basically what i'm asking for if any knows of a way to close this UserControls called from a method such as onDestroy that will also release the resources? 所以,基本上,我要问的是,是否有人知道从诸如onDestroy之类的方法中关闭此UserControls的方法,该方法也会释放资源?

And is there also a way that I can use this same method to shut down my background Workers? 还有一种方法可以使用相同的方法关闭后台工作人员吗?

You need to signal the background worker to stop and the background worker needs to make sure that is takes care of the signal. 您需要发信号通知后台工作人员停止,并且后台工作人员需要确保已处理好该信号。 Signalling can be implemented using various patterns, the simplest being: 可以使用各种模式来实现信令,最简单的方法是:

Derive all user controls you have from a basic control (or have them implement an interface) that contains a method named CloseControl . 从包含名为CloseControl的方法的基本控件(或使它们实现接口)派生所有用户控件。 In the CloseControl method, set a flag that signals the background worker to stop. CloseControl方法中,设置一个标志,指示后台工作程序停止。

Before closing the window that contains the user controls, call the CloseControl method on each of them. 关闭包含用户控件的窗口之前,请在每个用户控件上调用CloseControl方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM