I've got a class like this:
public class SecondaryThreadClass
{
private string str;
public SecondaryThreadClass ()
{
}
~SecondaryThreadClass(){
Console.WriteLine("Secondary class's instance was destroyed");
}
public void DoJobAsync(){
new Thread(() => {
// this.str = "Hello world";
// Console.WriteLine(this.str);
Console.WriteLine("Hello world");
}).Start();
}
}
When I uncomment those two lines and comment Console.WriteLine("Hello world"); instead my destructor never gets called. So it appears that if I use "this" inside a secondary-thread method my object doesn't get collected. The caller's code is here:
public override void ViewDidLoad ()
{
SecondaryThreadClass instance = new SecondaryThreadClass();
instance.DoJobAsync();
base.ViewDidLoad ();
}
How can I make GC collect those objects? I'm using MonoTouch if it matters.
Edit:
public void DoJobAsync(){
new Thread(() => {
this.str = "Hello world";
Console.WriteLine(this.str);
// Console.WriteLine("Hello world");
new Thread(() => {
Thread.Sleep(2000);
GC.Collect();
GC.WaitForPendingFinalizers();
}).Start();
}).Start();
}
This doesn't help either (timeout is needed to ensure that the first thread is finished before GC.Collect() is called).