Click here to Skip to main content
14,391,232 members
Rate this:
Please Sign up or sign in to 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();

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 20:21pm
v2
Comments
Thanks7872 1-Oct-13 1:14am
   
How do I thread this? What do you mean by thread here?
Rate this:
Please Sign up or sign in to vote.

Solution 2

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:

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.
   
v3
Rate this:
Please Sign up or sign in to vote.

Solution 1

You can use AsyncCallback[^], which has a good example on how to use it.
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

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.
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100