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 ? :
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();
}
}