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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T21:08:56+00:00 2026-05-13T21:08:56+00:00

I asked a question about building custom Thread Safe Generic List now I am

  • 0

I asked a question about building custom Thread Safe Generic List now I am trying to unit test it and I absolutely have no idea how to do that. Since the lock happens inside the ThreadSafeList class I am not sure how to make the list to lock for a period of time while I am try to mimic the multiple add call. Thanks.

Can_add_one_item_at_a_time

[Test]
public void Can_add_one_item_at_a_time() //this test won't pass
{
    //I am not sure how to do this test...
    var list = new ThreadSafeList<string>();

    //some how need to call lock and sleep inside list instance
    //say somehow list locks for 1 sec

    var ta = new Thread(x => list.Add("a"));
    ta.Start(); //does it need to aboard say before 1 sec if locked

    var tb = new Thread(x => list.Add("b"));
    tb.Start(); //does it need to aboard say before 1 sec if locked

    //it involves using GetSnapshot()
    //which is bad idea for unit testing I think
    var snapshot = list.GetSnapshot(); 
    Assert.IsFalse(snapshot.Contains("a"), "Should not contain a.");
    Assert.IsFalse(snapshot.Contains("b"), "Should not contain b.");
}

Snapshot_should_be_point_of_time_only

[Test]
public void Snapshot_should_be_point_of_time_only()
{
    var list = new ThreadSafeList<string>();
    var ta = new Thread(x => list.Add("a"));
    ta.Start();

    ta.Join();
    var snapshot = list.GetSnapshot();

    var tb = new Thread(x => list.Add("b"));
    tb.Start();

    var tc = new Thread(x => list.Add("c"));
    tc.Start();

    tb.Join();
    tc.Join();

    Assert.IsTrue(snapshot.Count == 1, "Snapshot should only contain 1 item.");
    Assert.IsFalse(snapshot.Contains("b"), "Should not contain a.");
    Assert.IsFalse(snapshot.Contains("c"), "Should not contain b.");
}

Instance method

public ThreadSafeList<T> Instance<T>()
{
    return new ThreadSafeList<T>();
}
  • 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-13T21:08:56+00:00Added an answer on May 13, 2026 at 9:08 pm

    Let’s look at your first test, Can_add_one_item_at_a_time.

    First of all, your exit conditions don’t make sense. Both items should be added, just one at a time. So of course your test will fail.

    You also don’t need to make a snapshot; remember, this is a test, nothing else is going to be touching the list while your test is running.

    Last but not least, you need to make sure that you aren’t trying to evaluate your exit conditions until all of the threads have actually finished. Simplest way is to use a counter and a wait event. Here’s an example:

    [Test]
    public void Can_add_from_multiple_threads()
    {
        const int MaxWorkers = 10;
    
        var list = new ThreadSafeList<int>(MaxWorkers);
        int remainingWorkers = MaxWorkers;
        var workCompletedEvent = new ManualResetEvent(false);
        for (int i = 0; i < MaxWorkers; i++)
        {
            int workerNum = i;  // Make a copy of local variable for next thread
            ThreadPool.QueueUserWorkItem(s =>
            {
                list.Add(workerNum);
                if (Interlocked.Decrement(ref remainingWorkers) == 0)
                    workCompletedEvent.Set();
            });
        }
        workCompletedEvent.WaitOne();
        workCompletedEvent.Close();
        for (int i = 0; i < MaxWorkers; i++)
        {
            Assert.IsTrue(list.Contains(i), "Element was not added");
        }
        Assert.AreEqual(MaxWorkers, list.Count,
            "List count does not match worker count.");
    }
    

    Now this does carry the possibility that the Add happens so quickly that no two threads will ever attempt to do it at the same time. No Refunds No Returns partially explained how to insert a conditional delay. I would actually define a special testing flag, instead of DEBUG. In your build configuration, add a flag called TEST, then add this to your ThreadSafeList class:

    public class ThreadSafeList<T>
    {
        // snip fields
    
        public void Add(T item)
        {
            lock (sync)
            {
                TestUtil.WaitStandardThreadDelay();
                innerList.Add(item);
            }
        }
    
        // snip other methods/properties
    }
    
    static class TestUtil
    {
        [Conditional("TEST")]
        public static void WaitStandardThreadDelay()
        {
            Thread.Sleep(1000);
        }
    }
    

    This will cause the Add method to wait 1 second before actually adding the item as long as the build configuration defines the TEST flag. The entire test should take at least 10 seconds; if it finishes any faster than that, something’s wrong.

    With that in mind, I’ll leave the second test up to you. It’s similar.

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

Sidebar

Related Questions

i have asked a question about manytomanyfield here which i solved but now a
I asked the question about multiple rows in a previous thread, but now I
Following on from a question I asked about escaping content when building a custom
I have tried looking though several of the already asked question about this topic
I asked a question about bigints yesterday which was kindly answered. However, I have
I asked a little while ago a question about rollback, I have a new
I have asked a question about how to avoiding to write the html in
I asked another question about HTML and PHP separation as I have seen references
I recently asked a question about building a SOAP message using the java provided
Just asked a question about linking Boost libraries in the make file. Thanks to

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.