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 7593955
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T21:18:00+00:00 2026-05-30T21:18:00+00:00

I’ve been debugging my program, because it throws Out Of Memory exceptions. After stripping

  • 0

I’ve been debugging my program, because it throws Out Of Memory exceptions.
After stripping it down, it looks like a Task is holding onto a reference although it is done.
Here is my stripped down code:

public class Program {
    static void Main(string[] args) {
        var cts = new CancellationTokenSource();
        ConsumeFiles(cts.Token);
    }

    public static void ConsumeFiles(CancellationToken ct) {
        while(true) {
            var dataSource = new Queue<byte[]>();
            for(int i = 0;i < 16;i++) {
                var block = new byte[4 * 1024 * 1024];
                for(int j = 0;j < block.Length;j++) block[j] = (byte)j;
                dataSource.Enqueue(block);
            }

            var cts = new CancellationTokenSource();
            ct.Register(() => cts.Cancel()); //Remove this line => No OOM

            Task.Factory.StartNew(() => { //Remove Task => No OOM
                var b = dataSource; //Remove this line => No OOM
            }).Wait();
        }
    }
}

In my unstripped code:
The CancellationTokenSource in Main is used to cancel the whole operation.
The one in ConsumeFiles is used to cancel a suboperation, in case something went wrong in some other suboperation in ConsumeFiles.

What do I need to do so that the old instance of dataSource is properly garbage collected?
And why doesn’t it work the way it is now?

  • 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-05-30T21:18:02+00:00Added an answer on May 30, 2026 at 9:18 pm

    It’s not the task holding onto a reference

    This

    var cts = new CancellationTokenSource();
    ct.Register(() => cts.Cancel());
    

    is your only problem.

    cts is the CancellationTokenSource that was created in your Main method. In each iteration of the loop, you are creating a new CancellationTokenSource and then registering a callback where you call Cancel on the new cts. When you register a callback, it’s passed into the token’s parent, which happens to be the token source in Main. Each time you register one, it will be added to the array, increasing it’s size as necessary.

    Because the token source in main is still in scope, it’s not eligible for garbage collection, and neither is the array of callbacks that it is holding onto internally.

    Here are type stats from windbg:

    1- After a minute or two:

    00787a68     1200        37560      Free
    6d6913b8     1785        49980 System.Threading.CancellationCallbackInfo
    6d64f468     1789        57248 System.Action
    6d64eb28     1788        71520 System.Threading.CancellationTokenSource
    6d6470cc       52    213910128 System.Byte[]
    Total 6881 objects
    

    2- A few minutes later:

    00787a68     1920        56496      Free
    6d6913b8     2943        82404 System.Threading.CancellationCallbackInfo
    6d64f468     2946        94272 System.Action
    6d64eb28     2946       117840 System.Threading.CancellationTokenSource
    6d6470cc       44    180355600 System.Byte[]
    Total 11064 objects
    

    3- A few more minutes:

    00787a68     3269        91514      Free
    6d6913b8     4975       139300 System.Threading.CancellationCallbackInfo
    6d64f468     4976       159232 System.Action
    6d64eb28     4978       199120 System.Threading.CancellationTokenSource
    6d6470cc       10     37748856 System.Byte[]
    Total 18465 objects
    

    Notice that each time I’ve run a stat on the heap, the number of allocated byte[] changes (because they are getting GC’d), where the number of CancellationTokenSource (the line where you new one up) types keeps increasing, along with the System.Action (the parameter you’ve passed to Register) and CancellationCallbackInfo (the internal data structure created by Register() to store the value).

    From the code you’ve given, it doesn’t make any sense to create a cancellation token source at all if you want to cancel multiple threads. You can pass the token parameter (ct) into other tasks you want to cancel. Even though it’s a value type, and will be copied, the pointer to the token source remains, and you can still cancel them all with a cts.Cancel() from Main. I’m not sure if that’s what you’re trying to do, though.

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

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I would like to run a str_replace or preg_replace which looks for certain words
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I would like to count the length of a string with PHP. The string
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am trying to render a haml file in a javascript response like so:

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.