Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Should I protect 'this' from deletion in its own member functions?

The use case:

class TheClient
{
  void funcClient()
  {   
     // Local objet with long process
     ClassLast  objServ1 = new ClassLast();

     // Starting ClassLast long process in separated thread
     Thread thCaller = new Thread( objServ1.FunctionThatLastALot ));
     thCaller.Start();

    // Now Leaving funcClient, the local objServ1 will be deleted (!)
  }
}

Question:
Does objServ1 may be deleted as soon as the functionClient ends (And I could apply the solution below) ?
Or is there an internal CSharp mechanism that prevents the deletion as long as its member is running ?

If the object is subject to deletion while running, do you thing this should be a solution ? :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class ClassLast 
{
  void FuncThatLastALot()
  {    
     // auto-referencing to prevent deletion
     ClassLast me = this;
     // …
     // Process and keep calm, we have time 
     // … 
  }  
}

>Solution :

Short Version: No. You dont need to add this kind of protection. The object will persist as long as it is needed, even if the creating function has been left. The thread will "keep it alive" to run the function and only let it be deleted AFTER its done with it. If you wanna have a little "proof of Concept"

public class Programm 
{
    public class TheClient
    {
        public void FuncCall()
        {
            ClassLast last = new();
            Thread thCaller = new Thread(last.FuncLastLot);
            thCaller.Start();
        }
    }

    public class ClassLast
    {
        public void FuncLastLot()
        {
            Thread.Sleep(5000);
            Console.WriteLine("Function End");
        }
    }

    static void Main(string[] args)
    {

        TheClient client = new TheClient();
        client.FuncCall();
        Console.WriteLine("Out of Function");
        Console.ReadLine();
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading