gpt4 book ai didi

c# - 如何处理大量的静态变量和集合?

转载 作者:太空宇宙 更新时间:2023-11-03 21:38:50 28 4
gpt4 key购买 nike

我制作了一个大型 Windows 应用程序,在 program.cs 类中我使用了很多静态变量大约 20 个,其中一些用于我在此过程中制作的大量对象。

我想知道我应该如何在应用程序结束时管理它,我应该在哪里以及如何调用它们处置。我制作了 GC.Collect 但这会挂起应用程序并降低性能。 当我调用 GC.Collect 时,它正在舔内存并挂起很长时间。

请让我知道我应该如何管理这个静态类、静态变量。从而提高性能。

最佳答案

我认为您使用 static 变量的方式是完全错误的,您可能误解了这个概念。

只有当您知道变量将在程序的整个生命周期中被访问时,您才应该将任何字段标记为 static,即只有当您终止程序时才会对它们进行 GC。

EDIT 在 C# 中,内存由 Garbage Collector 自动管理,程序员只需要知道创建的对象何时适用于 Garbage Collection。在 MSDN ducumentation明确提到,

C# employs automatic memory management, which frees developers from manually allocating and freeing the memory occupied by objects. Automatic memory management policies are implemented by a garbage collector. The memory management life cycle of an object is as follows:

  1. When the object is created, memory is allocated for it, the constructor is run, and the object is considered live.
  2. If the object, or any part of it, cannot be accessed by any possible continuation of execution, other than the running of destructors, the object is considered no longer in use, and it becomes eligible for destruction. The C# compiler and the garbage collector may choose to analyze code to determine which references to an object may be used in the future. For instance, if a local variable that is in scope is the only existing reference to an object, but that local variable is never referred to in any possible continuation of execution from the current execution point in the procedure, the garbage collector may (but is not required to) treat the object as no longer in use.
  3. Once the object is eligible for destruction, at some unspecified later time the destructor (Section 10.12) (if any) for the object is run. Unless overridden by explicit calls, the destructor for the object is run once only.
  4. Once the destructor for an object is run, if that object, or any part of it, cannot be accessed by any possible continuation of execution, including the running of destructors, the object is considered inaccessible and the object becomes eligible for collection.
  5. Finally, at some time after the object becomes eligible for collection, the garbage collector frees the memory associated with that object.

简单来说,如果一个对象没有更多的事件引用(范围尚未结束的指针)指向它,它就有资格进行 GC。

在您的情况下,static 变量 的范围延伸到程序的整个运行过程中,一旦您通过将这些引用分配给新对象或将它们分配给 来删除这些引用null 如果没有其他指向旧对象的事件引用处于事件状态,则旧对象将适用于 GC。

关于c# - 如何处理大量的静态变量和集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20441823/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com