简体   繁体   English

在C#中从计算机内存中删除字符串

[英]Delete string from computer memory in C#

I have to work with string because it has all the functions I have like check any letters of it, substring and so on. 我必须使用字符串,因为它具有我想要检查的所有字母,子字符串等所有功能。 After used string I need to delete it from computer memory. 使用完字符串后,我需要将其从计算机内存中删除。 I have already read about SecureString but I can not work with it because it has not a lot of functions. 我已经读过有关SecureString的信息,但是由于它没有很多功能,因此无法使用它。

Can anyone help me how to delete string from memory? 谁能帮我从内存中删除字符串? How can I solve it? 我该如何解决?

Both answers should have provided the correct answer for most cases, but in case your string value is considerably critical that you must remove it from the memory after using it, your best bet would be to use SecureString . 在大多数情况下,这两个答案都应该提供正确的答案,但是如果您的字符串值非常关键,以至在使用后必须将其从内存中删除,则最好的选择是使用SecureString

You have already stated that SecureString does not provide the methods you specifically need; 您已经说过SecureString没有提供您特别需要的方法。 in that case, you need to do some on your own. 在这种情况下,您需要自己做一些事情。 Luckily, .NET is open source and you can easily Copy-Paste the implementations you need from here . 幸运的是,.NET是开源的,您可以从此处轻松地复制粘贴所需的实现。 Make them as extensions of SecureString to use them. 使它们成为SecureString扩展以使用它们。

As long as those a dynamic strings, not compiled literals - you don't need to worry about "deleting" them, Garbage Collector will do it for you. 只要那些动态字符串而不是编译的文字-您无需担心“删除”它们,垃圾收集器将为您完成。 Strings are same as any other .net classes, so you don't need to manage memory they are allocating. 字符串与任何其他.net类相同,因此您无需管理它们分配的内存。

If you are worry about size of the memory your application takes at some periods of time - you can kindly force GC to collect all resources, that are not needed any more by calling System.GC.Collect() . 如果您担心应用程序需要花费一段时间的内存大小,可以通过调用System.GC.Collect()强制GC收集所有不再需要的资源。 But usually this is not needed. 但是通常不需要。

Also be aware, that calling System.GC.Collect() doesn't mean garbage collection will start right away - it means that GC will schedule collection some time soon. 另请注意,调用System.GC.Collect()并不意味着立即开始垃圾收集-这意味着GC将在不久的将来安排收集。

If you remove all references to the string, you can call System.GC.Collect() to force the Garbage Collector to run, although even then it's not guaranteed to run immediately, more like "Hey, GC, run as soon as you get the chance." 如果删除了对该字符串的所有引用,则可以调用System.GC.Collect()强制垃圾回收器运行,尽管即使这样也不能保证立即运行,就像“嘿,GC,一旦获得机会。” And it's really not recommended at all. 根本不建议这样做。 It can cause serious performance issues if you do it often. 如果经常这样做,可能会导致严重的性能问题。

If your string is really so critical that you don't even want it floating around in memory, SecureString really is your best bet. 如果您的字符串确实非常重要,以至于您甚至都不希望它在内存中浮动,那么SecureString确实是您的最佳选择。 You'll just have to re-implement functions you need (like .SubString()) for it. 您只需要重新实现所需的功能(例如.SubString())即可。

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

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