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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T11:13:39+00:00 2026-05-20T11:13:39+00:00

I recently read this article Safe Thread Synchronization as I was curious about the

  • 0

I recently read this article Safe Thread Synchronization as I was curious about the thread safety of calls made from a finaliser. I wrote the following code to test access to a static thread safe collection from a finaliser.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GCThreadTest
{
    class Program
    {
        static class FinaliserCollection
        {
            private static Queue<int> s_ItemQueue = new Queue<int>();
            private static System.Object s_Lock = new System.Object();

            public static void AddItem(int itemValue)
            {
                lock(s_Lock)
                {
                    s_ItemQueue.Enqueue(itemValue);
                }
            }

            public static bool TryGetItem(out int item)
            {
                lock(s_Lock)
                {
                    if (s_ItemQueue.Count <= 0)
                    {
                        item = -1;
                        return false;
                    }

                    item = s_ItemQueue.Dequeue();
                    return true;
                }
            }
        }

        class FinaliserObject
        {
            private int m_ItemValue;

            public FinaliserObject(int itemValue)
            {
                m_ItemValue = itemValue;
            }

            ~FinaliserObject()
            {
                FinaliserCollection.AddItem(m_ItemValue);
            }
        }

        static void Main(string[] args)
        {
            int itemValueIn = 0;
            int itemValueOut = 0;

            while (itemValueOut < 10000)
            {
                System.Threading.ThreadPool.QueueUserWorkItem
                    (delegate(object value)
                    {
                        new FinaliserObject((int)value);

                        System.Threading.Thread.Sleep(5);

                    }, itemValueIn);

                itemValueIn = itemValueIn + 1;

                // This seems to stop finaliser from
                // being called?
                // System.Threading.Thread.Sleep(5);

                int tempItemValueOut = -1;
                if (FinaliserCollection.TryGetItem(out tempItemValueOut))
                    itemValueOut = tempItemValueOut;
            }

            System.Console.WriteLine("Finished after {0} items created", itemValueOut);
            System.Console.ReadLine();
        }
    }
}

Without the ‘Sleep’ call in the while loop this code seems to run fine but is it really safe from deadlocking? Would it ever be possible for a finaliser call to be made while a queued thread pool item is accessing the static collection? Why does adding the ‘Sleep’ to the main threads while loop appear to stop all finalisers from being called?

  • 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-20T11:13:40+00:00Added an answer on May 20, 2026 at 11:13 am

    Wow. What the… This is the most bizarre piece of code I’ve ever seen. @.@

    First of all, what finalizer call are you referring to? The only finalizer I see is the finalizer for the FinaliserObject, which will be called 10,000 times, and can be called independently of whatever’s going on on the static collection. I.E. yes, those objects can be destroyed while other objects are being dequeued from the collection. This isn’t an issue.

    The static collection itself won’t be cleaned up until the app itself exits.

    Keep in mind that there’s absolutely no guarantee when or if those finalizers will be called before the app itself exits. Your static collection could be completely empty when you exit.

    Worse, you’re assigning itemValueOut to whatever the last value you pull out of the queue is… which is NOT the number of items created, as you imply in your WriteLine(). Because those destructors are called in any possible order, you could theoretically add to the queue 10,000, 9,999, 9,998, … 2, 1, in that order.

    Which is further an issue, because you’re removing from the queue 10,000 times, but on the last loop, it’s very possible there won’t be an object to dequeue, in which case you’re guaranteed to get -1 for the number of items returned (even if the other 9,999 items worked successfully).

    To answer your question, this code cannot deadlock. A deadlock would happen if AddItem() called TryGetItem(), but those locks are pretty much guaranteed to keep each other out of the static collection while adding or removing items.

    Where you’re tempting fate is that you can exit your app without all of the FinaliserObjects having added themselves to the queue. Meaning one of the finalizers could fire and try to add to the FinaliserCollection, but the FinaliserCollection has already been disposed. What you’re doing in the finaliser is terrible.

    But yes, a finalizer call can happen while you’re calling FinaliserCollection.TryGetItem(). The finalizer will block and wait until TryGetItem() emerges from the lock(), at which point it will add another item. This is not an issue.

    As for the sleep() command, you’re probably just throwing the timing of the garbage collection off. Remember, your objects won’t be collected/finalized until the GC decides it needs the resources.

    Sorry for being so emphatic… I know you’re just trying to test a concept but I really don’t understand why you would want to do what you’re trying to do in the finalizer. If there’s really a legitimate goal here, doing it in the finalizer is not the correct answer.

    Edit

    From what I’m reading and what Sasha is saying, no you will not have a deadlock. The finalizer thread may be blocked waiting for the lock, but the GC will not wait for the finalizer, and will thus unsuspend the threads, allowing the locks to be released.

    In any case, this is a very strong argument for why you shouldn’t be making calls like this in a finalizer… the finalizer is only for releasing unmanaged resources. Anything else is playing roulette.

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

Sidebar

Related Questions

I have recently read the safe bool idiom article. I had seen this technique
I recently read an article talking about the Java annotations, and on this latter
I've recently read an article http://www.ravelrumba.com/blog/static-cookieless-domain/ about Serving Static Content from a Cookieless Domain
I recently read this article from Neil Griffin Making Distinctions Between Different Kinds of
I`ve recently read this article about a user losing data on EC2 when dealing
I recently read a post online about rotating text with css. This appealed to
I recently read an article about password hashing . How are MD5 or SHA1
I recently read an article about c#-5 and new & nice asynchronous programming features
Recently, I read this article: http://download.oracle.com/javase/tutorial/extra/generics/wildcards.html My question is, instead of creating a method
I recently read an article on Wikipedia about Design Pattern So far I've done

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.