c# – 等待线程完成
发布时间:2020-12-15 20:03:34 所属栏目:百科 来源:网络整理
导读:private void button1_Click(object sender,EventArgs e) { for (int i = 0; i 15; i++) { Thread nova = new Thread(Method); nova.Start(); } listBox1.Items.Add("Some text"); } private void Method() { for (int i = 0; i 15; i++) { Console.WriteLin
private void button1_Click(object sender,EventArgs e) { for (int i = 0; i < 15; i++) { Thread nova = new Thread(Method); nova.Start(); } listBox1.Items.Add("Some text"); } private void Method() { for (int i = 0; i < 15; i++) { Console.WriteLine(i); } } 这段代码写的:有些文字然后是数字111222333 ….. 解决方法
我建议使用TPL来完成这项工作.你不需要产生这么多线程.默认情况下,TPL将使用线程池:
using System; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { private const int TaskCount = 15; static void Main(string[] args) { var tasks = new Task[TaskCount]; for (var index = 0; index < TaskCount; index++) { tasks[index] = Task.Factory.StartNew(Method); } Task.WaitAll(tasks); Console.WriteLine("Some text"); } private static void Method() { for (int i = 0; i < 15; i++) { Console.WriteLine(i); } } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |