Search code examples
c#multithreadingthread-abort

Why my Thread does not stop?


I have the following code, where I start a Thread using a ParameterizedThreadStart object as constructor argument:

static object obj = new object();

static void Main(string[] args)
{
    ParameterizedThreadStart start = (o) =>
    {
        ThreadTest(o);
    };

    var t = new Thread(() => start(obj));
    t.Name = "t";
    t.Start();

    Thread.Sleep(3000);
    obj = null;

    // Why the Thread (t) continue here??
    Console.ReadKey();
}


private static void ThreadTest(object o)
{
    while (o != null)
    {
        Console.WriteLine(Thread.CurrentThread.Name);
        Thread.Sleep(1000);
    }
}

After I set obj to null in the ThreadTest method the argument o is still a valid object, why?
How can I set the argument o to null using obj?

I would prefer not to use Thread.Abort


Solution

  • Because in C#, references are passed by value.

    So, changing obj to refer to NULL in Main will not change the object to which o refers in ThreadTest.

    Instead, you should keep both methods referring to the same object, and just change a property of the object to signal that the thread should exit.