Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9130497
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T07:58:32+00:00 2026-06-17T07:58:32+00:00

When looking for a memory- and handleleak in a .NET/WCF/Windows Service I noticed strange

  • 0

When looking for a memory- and handleleak in a .NET/WCF/Windows Service I noticed strange behavior that I cannot explain.
Here the setup and the resolution. What I am looking for would be an explanation for the observed behavior.

I installed a Windows Service.

I started the service.

I called a simple method with a transactional WCF call (new channel per call – no caching).

For each call about 2 handles remain in memory.

This can be observed if the following items are applicable:

  1. It is a Windows Service; don’t run it as a Console App.
  2. Use a Transaction (separate process or machine tested only) to call the WCF method.
  3. Before calling ServiceBase.Run(servicesToRun); instantiate XmlSerializer with some type.
  4. The type is a custom type. It does not occur with new XmlSerializer(typeof(string)) or new XmlSerializer(typeof(XmlDocument)). No call to serialize is necessary. It is enough if the custom type has only a string as property (no handles anywhere!)
  5. Creating a static XmlSerialization.dll using i.e. SGen.exe will not produce this problem.

My Code already includes the fix:

Use XmlSerializer earliest in OnStart():

Program.cs

WindowsService winSvc = new WindowsService();
ServiceBase[] servicesToRun = new ServiceBase[]{winSvc};                    
ServiceBase.Run(servicesToRun);

WindowsService.cs

internal sealed class WindowsService : ServiceBase
{
    private ServiceHost wcfServiceHost = null;

    internal WindowsService()
    {
        AutoLog = true;
        CanStop = true;
        CanShutdown = true;
        CanPauseAndContinue = false;
    }

    internal void StartWcfService()
    {
        wcfServiceHost = new ServiceHost(typeof(DemoService));
        wcfServiceHost.Open();
    }

    protected override void Dispose(bool disposing)
    {
        if (wcfServiceHost != null)
        {
            wcfServiceHost.Close();
        }

        base.Dispose(disposing);
    }

    protected override void OnStart(string[] args)
    {
        new XmlSerializer(typeof(MyType));

        StartWcfService();
    }
}

DemoService.cs

[ServiceBehavior
    (
        InstanceContextMode = InstanceContextMode.PerSession,
        TransactionAutoCompleteOnSessionClose = false,
        IncludeExceptionDetailInFaults = true
    )
]
public sealed class DemoService : IDemoService
{           
    [TransactionFlow(TransactionFlowOption.Allowed)]
    [OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
    public int Add(int a, int b)
    {
        return a + b;
    }
}

Client.cs:

IChannelFactory<IDemoService> channelFactory = new ChannelFactory<IDemoService>("defaultClientConfiguration");
IDisposable channel = null;
for (int index = 0; index < 5000; index++)
{
    using
    (
        channel = (IDisposable)channelFactory.CreateChannel(new EndpointAddress("net.tcp://localhost:23456/DemoService")))
        {                       
        IDemoService demoService = (IDemoService)channel;
        using (TransactionScope tx = new TransactionScope(TransactionScopeOption.RequiresNew))
        {
            demoService.Add(3, 9);
            tx.Complete();  
        }
    )
}

Can someone explain this behavior?

Please note, I’m not interested in finding a way to avoid the leak (I already know how to do this) but in an explanation (i.e. WHY is it happening).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T07:58:33+00:00Added an answer on June 17, 2026 at 7:58 am

    I think some of the inner workings do this question justice. I do this from the back of my head, since I ran into this problem as well some time ago, and it took me a day to track back including extensive use of Reflector and ANTS Memory profiler (at my previous company)… here goes:

    What the XML Serializer internally does is it creates a class (let’s call it ‘A’) using System.Reflection.Emit that accepts the type you pass to it. Constructing such a class costs a lot of time relatively speaking, and are reusable since types don’t change. Because of this, the constructed types are stored in a dictionary, e.g. it ends up with some Dictionary .

    For known (basic) types, the serializer code is fixed, e.g. the serialization of a string is not going to change no matter how many times you restart your application. Note the difference with ‘A’ where any type that’s unknown to the serialization factory till it’s first passed to the XMLSerializer.

    The first time the type is used by the XMLSerializer, this process takes place for both the type you pass and all types it needs (e.g. all fields and properties that require serialization).

    About the leak… When you call the ChannelFactory, it constructs serializer if it doesn’t exist yet. For that it checks if the serializer already exists in the Dictionary and if not, creates one by making an instance of ISomeSerializerType.

    For some stupid reason, there is a bug in the factory that constructs a new serializer without storing it in the dictionary. Once constructed, you end up with a new type – which shows up as a leak (remember: types can never be unloaded) – even though the objects are correctly disposed. When you use XMLSerializer first or create a static class, it correctly uses the Dictionary cache, which means it won’t leak. So there you have it, it is a bug. I used to have access to ANTS Memory Profiler, which showed this quite nicely.

    Hope this explains.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm looking for a language that, while being flexible and very light on memory
I am looking for an equivalent of the data returned by memory on windows
I acknoledged a memory leak when I saw that my small service, without any
I'm looking for some tool/app/tweak that can generate low memory warning on iPhone (jailbroken).
We are looking to implement in memory session replication. Before we do that our
I'm pretty sure that UIImagePNGRepresentation([UIImage imageWithCGImage:imageRef]) is the cause of random-looking memory leaks when
I'm looking at a competition that is looking for memory safety vulnerability mitigation techniques.
I'm looking for a real time memory tracker library (or considering writing one) that
I recently was looking at some code that uses SetLength to allocate memory for
I'm looking into the memory model a little more and am struggling with understanding

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.