0

I am trying to return the EmployeeModel object after assigning it in thread scope and running it. The return_Employee Object is returning me Null values even after running. AddEmployee is another method of return type EmployeeModel object.

I actually need thread method to have return type so as to use it in unit testing project.

       public EmployeeModel AddEmployeeUsingThread(int emp_ID, decimal basicPay, decimal deductions, 
       decimal taxablePay, decimal NetPay)
       {

        EmployeeModel return_Employee=null;

        var thread = new Thread(()=>
        {
            return_Employee= AddEmployee(emp_ID, basicPay, deductions, taxablePay, NetPay);
        });
        thread.Start();

        return return_Employee;
    }
  • 2
    You are not waiting for the thread to complete, the variable is almost certainly still null at the point you return the value from it. Since you have to wait for the thread to complete, you should just remove the threading altogether and call AddEmployee directly, otherwise you will have to convert this to using a `Task`, that will return the employee sometime in the future when it has completed. – Lasse V. Karlsen Nov 06 '20 at 07:44
  • refering to this post https://stackoverflow.com/questions/1314155/returning-a-value-from-thread, this is the way I followed to get back the result/ return object without using async or task. problem is... other methods are working fine in threads its just not in AddEmployee Case. Can you refactor this code using Task generic ? – InterStellaR Nov 06 '20 at 09:22
  • @InterStellaR `thread.Join();` method call is missing after the `thread.Start();` – Peter Csala Nov 06 '20 at 09:41
  • 1
    Yes, to complete the code and still using a thread you can add `thread.Join();`, but I don't see the point of even using a thread here. A thread is useful if you can do other stuff while the thread is executing. In this case there is no point as you will pause one thread waiting for another that you just started, to complete. I would simply call the method directly without involving a thread as you gain absolutely nothing from this. – Lasse V. Karlsen Nov 06 '20 at 09:43
  • nah actually I was doing comparison the execution time between using thread and non thread ( default method ) as part of my training exercise. And That comparison has to be done over NUnit Test while validation the return objects with the expected objects. ok ill add thread.join() and see. – InterStellaR Nov 06 '20 at 10:07

0 Answers0