Search code examples
c#multithreadinggarbage-collectionstringbuilderusing

How do I ensure that the StringBuilder object is GCed in a multi-threaded environment? (Given that I can't use the using Keyword)?


EDIT :- How do I ensure that the StringBuilder object is GC'ed in a multi-threaded environment? (Given that I can't use the using Keyword)?

I'm using StringBuilder across multiple threads and I create a new instance of StringBuilder for each thread being called.

I'm concerned about the performance, specifically the memory it is taking for so many instances of StringBuilder being created.

Is there an alternative to make sure the GC frees the memory for me? (Like calling Dispose etc.)

EDIT: The StringBuilder does not implement IDisposable, so I cant use the using keyword.

EDIT: I don't want to force the GC.Collect() since there are multiple threads running at the same time, and they're sharing resources between them. Some of these threads are lying dormant and are just listening for events to turn active again.


Solution

  • Another approach to consider is to have thread specific cache of string builder object(s). Assuming you are not manually spawning a new thread every time (i.e. threads are not getting created and destroyed, and are instead coming from a thread pool) following implementation of internal StringBuilderCache class in .Net framework may be a good starting point -

    http://referencesource.microsoft.com/#mscorlib/system/text/stringbuildercache.cs

    A more sophisticated implementation for reference can be found at - http://source.roslyn.codeplex.com/#Microsoft.CodeAnalysis.Workspaces/Formatting/StringBuilderPool.cs