Click here to Skip to main content
15,882,163 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
How do I thread a simple method and return its results?
For example, I have a class called Math, a single method that takes two ints as params and returns a int result. How do I thread this and get the result to be used later in the application?


Thread thread = new Thread(() => m.SumTest(5));
thread.Start();

C#
public class Maths
    {
        public int num1;
        public int num2;
        Random r = new Random();
        public void Divide()
        {
            for (int i = 0; i < 100000; i++)
            {
                num1 = r.Next(1, 2);
                num2 = r.Next(1, 2);
                int result = num1 / num2;
                Console.WriteLine(result);
                num1 = 0;
                num2 = 0;
            }

        }
        public int SumTest(int max)
        {
            int answer = 0;

            for (int i = 0; i < max; i++)
            {
                answer += i;
            }

            return answer;

        }

    }
Posted
Updated 30-Sep-13 19:21pm
v2
Comments
Thanks7872 1-Oct-13 1:14am    
How do I thread this? What do you mean by thread here?

You can use Task in c# 4.0 for threading. Task take care of threading internally so it is safer than dealing with threads.

Example on how to work on your program using Task is:

C#
Task<int> t1 = Task<int>.Factory.StartNew(() => m.SumTest(5));
Task t2 = Task.Factory.StartNew(() => m.Divide());
Task.WaitAll(t1, t2);  //this will wait till t1 and t2 get finished.
var sumResult = t1.Result; //get the result of SumTest method like this.
 
Share this answer
 
v3
You can use AsyncCallback[^], which has a good example on how to use it.
 
Share this answer
 
when you call thread and start and join it

you use a call back method and operating system automatically return it

if you have set response time for threads.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900