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

  • Home
  • SEARCH
  • 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 329205
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T09:33:59+00:00 2026-05-12T09:33:59+00:00

I have an object in C# on which I need to execute a method

  • 0

I have an object in C# on which I need to execute a method on a regular basis. I would like this method to be executed only when other people are using my object, as soon as people stop using my object I would like this background operation to stop.

So here is a simple example is this (which is broken):

class Fish
{
    public Fish()
    {
        Thread t = new Thread(new ThreadStart(BackgroundWork));     
        t.IsBackground = true;
        t.Start();
    }

    public void BackgroundWork()
    {
        while(true)
        {
            this.Swim(); 
            Thread.Sleep(1000); 
        }
    }


    public void Swim()
    {
         Console.WriteLine("The fish is Swimming"); 
    }
}

The problem is that if I new a Fish object anywhere, it never gets garbage collected, cause there is a background thread referencing it. Here is an illustrated version of broken code.

public void DoStuff()
{ 
   Fish f = new Fish();
}
// after existing from this method my Fish object keeps on swimming. 

I know that the Fish object should be disposable and I should clean up the thread on dispose, but I have no control over my callers and can not ensure dispose is called.

How do I work around this problem and ensure the background threads are automatically disposed even if Dispose is not called explicitly?

  • 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-12T09:33:59+00:00Added an answer on May 12, 2026 at 9:33 am

    Here is my proposed solution to this problem:

    class Fish : IDisposable 
    {
        class Swimmer
        {
            Thread t; 
            WeakReference fishRef;
            public ManualResetEvent terminate = new ManualResetEvent(false);
    
            public Swimmer(Fish3 fish)
            {
                this.fishRef = new WeakReference(fish);
                t = new Thread(new ThreadStart(BackgroundWork));    
                t.IsBackground = true;
                t.Start();
            } 
    
            public void BackgroundWork()
            {
                bool done = false;
                while(!done)
                {
                    done = Swim(); 
                    if (!done) 
                    {
                        done = terminate.WaitOne(1000, false);
                    } 
                }
            }
    
            // this is pulled out into a helper method to ensure 
            // the Fish object is referenced for the minimal amount of time
            private bool Swim()
            {
                bool done;
    
                Fish fish = Fish; 
                if (fish != null)
                {
                    fish.Swim(); 
                    done = false;
                }
                else 
                {
                    done = true;
                }
                return done;
            }
    
            public Fish Fish
            {
                get { return fishRef.Target as Fish3; }
            }
        }
    
        Swimmer swimmer;
    
        public Fish()
        {
                swimmer = new Swimmer(this);
        }
    
        public void Swim()
        {
            Console.WriteLine("The third fish is Swimming"); 
        }
    
        volatile bool disposed = false;
    
        public void Dispose()
        {
            if (!disposed)
            {
                swimmer.terminate.Set();
                disposed = true;
                GC.SuppressFinalize(this);
            }       
        }
    
        ~Fish() 
        {
            if(!disposed)
            {
                Dispose();
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 326k
  • Answers 326k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Here a solution using a JSON call to google ajax… May 14, 2026 at 1:42 am
  • Editorial Team
    Editorial Team added an answer <xsl:template match="tag"> ... <xsl:value-of select="normalize-space(.)" /> ... </xsl:template> In fact,… May 14, 2026 at 1:41 am
  • Editorial Team
    Editorial Team added an answer By default, an Applet can only connect to the same… May 14, 2026 at 1:41 am

Related Questions

I have an application in C# .NET which has a MainForm and a few
I have some extra functionality i need to add which includes adding a new
I have looked for a good example of a Builder pattern (in C#), but
I have a COM object that I'm trying to use from C++ (not .NET),

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.