本文介绍了线程返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何编写一个简单的方法并返回其结果? 例如,我有一个名为Math的类,一个采用两个整数作为参数并返回一个int结果的方法。如何对此进行编程并将结果用于稍后在应用程序中使用? 线程线程=新线程(()= > m.SumTest(5)); thread.Start();
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; } }推荐答案
您可以在c#4.0中使用任务穿线。任务在内部处理线程,因此它比处理线程更安全。 关于如何使用任务处理程序的示例是: 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.
您可以使用 AsyncCallback [ ^ ],其中有一个很好的例子如何使用它。 You can use AsyncCallback[^], which has a good example on how to use it.
当你调用线程并开始加入它时 你使用回调方法和操作系统自动返回它 如果你设置了线程的响应时间。 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.
更多推荐
线程返回值
发布评论