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 use my object, as soon as people stop using my object. I would like this background operation to stop.
So here is a simple example: 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 am new to the Fish object anywhere, it will never collect garbage because there is a background thread referencing it. Here is an illustrated version of the broken code.
public void DoStuff() { Fish f = new Fish(); }
I know that the Fish object must be disposable, and I must clear the stream at the disposal, but I do not control my subscribers and cannot guarantee that dispose is called.
How can I get around this problem and ensure that background threads are automatically deleted, even if Dispose is not explicitly called?
source share