- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
当使用来自 UI 的输入事件销毁和重建分配大量内存的控件时,我一直遇到问题。
显然,将窗口的内容设置为空不足以释放所包含的控件正在使用的内存。它最终会被GCed。但是随着用于销毁和构造控件的输入事件越来越频繁,GC 似乎会跳过一些对象。
我把它分解成这个例子:
XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" x:Name="window" MouseMove="window_MouseMove">
</Window>
C#:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
private class HeavyObject : UserControl
{
private byte[] x = new byte[750000000];
public HeavyObject()
{
for (int i = 0; i++ < 99999999; ) { } // just so we can follow visually in Process Explorer
Content = "Peekaboo!"; // change Content to el cheapo re-trigger MouseMove
}
}
public MainWindow()
{
InitializeComponent();
//Works 1:
//while (true)
//{
// window.Content = null;
// window.Content = new HeavyObject();
//}
}
private void window_MouseMove(object sender, MouseEventArgs e)
{
if (window.Content == null)
{
GC.Collect();
GC.WaitForPendingFinalizers();
// Works 2:
//new HeavyObject();
//window.Content = "Peekaboo!"; // change Content to el cheapo re-trigger MouseMove
//return;
window.Content = new HeavyObject();
}
else
{
window.Content = null;
}
}
}
}
这确实会在每个 MouseMove 事件中分配一个大约 750MB 的对象 (HeavyObject) 并将其作为主窗口的内容。如果 Cursor 在 Window 上保持静止,则 Content 更改将无休止地重新触发事件。对 HeavyObject 的引用在其下一次构造之前被清空,并触发对其剩余部分进行 GC 的徒劳尝试。
我们在 ProcessExplorer/Taskman 中看到的是,有时分配了 1.5GB 或更多。如果没有,请疯狂移动鼠标离开并重新进入窗口。如果您在没有 LARGEADDRESSAWARE 的情况下针对 x86 进行编译,您将得到一个 OutOfMemoryException(限制为 ~1.3GB)。
如果您在不使用鼠标输入的情况下在无限循环中分配 HeavyObject(取消注释部分“Works 1”),或者如果您通过鼠标输入触发分配但不将对象放入视觉对象,则不会遇到此行为树(取消注释部分“Works 2”)。
所以我想这与视觉树延迟释放资源有关。但是还有一个奇怪的效果:如果光标在窗口外时消耗了 1.5GB,GC 似乎不会启动,直到再次触发 MouseMove。至少,只要没有进一步的事件被触发,内存消耗似乎就会稳定下来。因此,要么在某处留下了长期存在的引用,要么 GC 在没有事件时变得懒惰。
我觉得很奇怪。你能弄清楚发生了什么吗?
编辑:正如 BalamBalam 评论的那样:在销毁控件之前可以取消引用控件背后的数据。那将是 B 计划。不过也许有更通用的解决方案。
说这样的控件是糟糕的代码是没有帮助的。我想知道为什么如果我在取消引用后将 UI 单独放置几个 Ticks,那么我没有引用的对象会被 GCed,但如果另一个对象(必须由用户输入创建)立即接受它,那么它会永远徘徊地方。
最佳答案
好吧,我想我可能知道这里发生了什么。不过要加少许盐……
我稍微修改了你的代码。
Xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" x:Name="window" MouseDown="window_MouseDown">
</Window>
代码隐藏
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
private class HeavyObject : UserControl
{
private byte[] x = new byte[750000000];
public HeavyObject()
{
for (int i = 0; i < 750000000; i++ )
{
unchecked
{
x[i] = (byte)i;
}
}
// Release optimisation will not compile the array
// unless you initialize and use it.
Content = "Loadss a memory!! " + x[1] + x[1000];
}
}
const string msg = " ... nulled the HeavyObject ...";
public MainWindow()
{
InitializeComponent();
window.Content = msg;
}
private void window_MouseDown(object sender, MouseEventArgs e)
{
if (window.Content.Equals(msg))
{
window.Content = new HeavyObject();
}
else
{
window.Content = msg;
}
}
}
}
现在运行它并点击窗口。我将代码修改为不使用 GC.Collect() 并在按下鼠标时设置内存。我在 Release模式 下编译并在没有调试器 的情况下运行。
在窗口上慢慢点击。
第一次单击时,您会看到内存使用量增加了 750MBytes。随后的点击会在 .. Nulled the heavy object..
之间切换消息和 Loads a memory!
只要你慢慢点击。分配和释放内存时会有轻微的滞后。内存使用量不应超过 750MBytes,但当重对象为空时它也不会减少。这是设计使然 GC Large Object Heap is lazy and collects large object memory when new large object memory is needed .来自 MSDN:
If I don't have enough free space to accommodate the large object allocation requests, I will first attempt to acquire more segments from the OS. If that fails, then I will trigger a generation 2 garbage collection in hope of freeing up some space.
在窗口上快速点击
大约 20 次点击。怎么了?在我的 PC 上,内存使用率没有上升,但主窗口现在不再更新消息。它卡住了。我没有遇到内存不足异常,我系统的整体内存使用率保持不变。
在窗口上使用 MouseMove 给系统加压
现在通过更改此 Xaml 将 MouseDown 替换为 MouseMove 事件(根据您的问题代码):
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" x:Name="window" MouseMove="window_MouseDown">
</Window>
我可以将鼠标移到它上面一段时间,但最终它会抛出 OutofMemoryException。强制异常的一个好方法是进行多次移动,然后尝试最大化窗口。
理论
好的,这就是我的理论。当您的 UI 线程在消息循环事件 (MouseMove) 中创建和删除内存时,垃圾收集器无法跟上。大型对象堆上的垃圾收集已完成 when memory is needed .这也是一项昂贵的任务,因此应尽可能少地执行。
当在 MouseMove 中执行时,我们注意到快速单击开/关/开/关时的滞后变得更加明显。如果要分配另一个大对象,根据该 MSDN 文章,GC 将尝试收集(如果内存不可用)或开始使用磁盘。
System Is in Low Memory Situation: This happens when I receive the high memory notification from the OS. If I think doing a generation 2 GC will be productive, I will trigger one.
现在这部分很有趣,我猜这里是
Finally, as of right now, the LOH is not compacted as a part of collection, but that is an implementation detail that should not be relied on. So to make sure something is not moved by the GC, always pin it. Now take your newfound LOH knowledge and go take control of the heap.
因此,如果大对象堆未被压缩,并且您在紧密循环中请求多个大对象,是否有可能集合导致碎片化,最终导致 OutOfMemoryException,即使理论上应该有足够的内存?
解决方案
让我们稍微释放 UI 线程,让 GC 空间喘口气。将分配代码包装在异步 Dispatcher 调用中并使用低优先级,例如 SystemIdle。这样,它将仅在 UI 线程空闲时分配内存。
private void window_MouseDown(object sender, MouseEventArgs e)
{
Dispatcher.BeginInvoke((ThreadStart)delegate()
{
if (window.Content.Equals(msg))
{
window.Content = new HeavyObject();
}
else
{
window.Content = msg;
}
}, DispatcherPriority.ApplicationIdle);
}
使用它我可以在整个表单上移动鼠标指针并且它永远不会抛出 OutOfMemoryException。它是否真的有效或已经“解决”了我不知道的问题,但它值得测试。
总结
关于c# - 重型 WPF 控件如何以一种确定的方式使用一个空闲内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8988118/
我一直在阅读有关汇编函数的内容,但对于是使用进入和退出还是仅使用调用/返回指令来快速执行,我感到很困惑。一种方式快而另一种方式更小吗?例如,在不内联函数的情况下,在汇编中执行此操作的最快(stdcal
我正在处理一个元组列表,如下所示: res = [('stori', 'JJ'), ('man', 'NN'), ('unnatur', 'JJ'), ('feel', 'NN'), ('pig',
最近我一直在做很多网络或 IO 绑定(bind)操作,使用线程有助于加快代码速度。我注意到我一直在一遍又一遍地编写这样的代码: threads = [] for machine, user, data
假设我有一个名为 user_stats 的资源,其中包含用户拥有的帖子、评论、喜欢和关注者的数量。是否有一种 RESTful 方式只询问该统计数据的一部分(即,对于 user_stats/3,请告诉我
我有一个简单的 api,它的工作原理是这样的: 用户创建一个请求 ( POST /requests ) 另一个用户检索所有请求 ( GET /requests ) 然后向请求添加报价 ( POST /
考虑以下 CDK Python 中的示例(对于这个问题,不需要 AWS 知识,这应该对基本上任何构建器模式都有效,我只是在这个示例中使用 CDK,因为我使用这个库遇到了这个问题。): from aws
Scala 中管理对象池的首选方法是什么? 我需要单线程创建和删除大规模对象(不需要同步)。在 C++ 中,我使用了静态对象数组。 在 Scala 中处理它的惯用和有效方法是什么? 最佳答案 我会把它
我有一个带有一些内置方法的类。这是该类的抽象示例: class Foo: def __init__(self): self.a = 0 self.b = 0
返回和检查方法执行的 Pythonic 方式 我目前在 python 代码中使用 golang 编码风格,决定移动 pythonic 方式 例子: import sys from typing imp
我正在开发一个 RESTful API。其中一个 URL 允许调用者通过 id 请求特定人员的记录。 返回该 id 不存在的记录的常规值是什么?服务器是否应该发回一个空对象或者一个 404,或者其他什
我正在使用 pathlib.Path() 检查文件是否存在,并使用 rasterio 将其作为图像打开. filename = pathlib.Path("./my_file-name.tif") 但
我正在寻找一种 Pythonic 方式来从列表和字典创建嵌套字典。以下两个语句产生相同的结果: a = [3, 4] b = {'a': 1, 'b': 2} c = dict(zip(b, a))
我有一个正在操裁剪理设备的脚本。设备有时会发生物理故障,当它发生时,我想重置设备并继续执行脚本。我有这个: while True: do_device_control() device
做组合别名的最pythonic和正确的方法是什么? 这是一个假设的场景: class House: def cleanup(self, arg1, arg2, kwarg1=False):
我正在开发一个小型客户端服务器程序来收集订单。我想以“REST(ful)方式”来做到这一点。 我想做的是: 收集所有订单行(产品和数量)并将完整订单发送到服务器 目前我看到有两种选择: 将每个订单行发
我知道在 Groovy 中您可以使用字符串调用类/对象上的方法。例如: Foo."get"(1) /* or */ String meth = "get" Foo."$meth"(1) 有没有办法
在 ECMAScript6 中,您可以使用扩展运算符来解构这样的对象 const {a, ...rest} = obj; 它将 obj 浅拷贝到 rest,不带属性 a。 有没有一种干净的方法可以在
我有几个函数返回数字或None。我希望我的包装函数返回第一个不是 None 的结果。除了下面的方法之外,还有其他方法吗? def func1(): return None def func2(
假设我想设计一个 REST api 来讨论歌曲、专辑和艺术家(实际上我就是这样做的,就像我之前的 1312414 个人一样)。 歌曲资源始终与其所属专辑相关联。相反,专辑资源与其包含的所有歌曲相关联。
这是我认为必须经常出现的问题,但我一直无法找到一个好的解决方案。假设我有一个函数,它可以作为参数传递一个开放资源(如文件或数据库连接对象),或者需要自己创建一个。如果函数需要自己打开文件,最佳实践通常
我是一名优秀的程序员,十分优秀!