线程返回值

编程入门 行业动态 更新时间:2024-10-27 21:20:03
本文介绍了线程返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何编写一个简单的方法并返回其结果? 例如,我有一个名为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.

更多推荐

线程返回值

本文发布于:2023-10-26 14:41:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530441.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   返回值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!