加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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 …..
我想它写111122223333 ….然后在最后一些文字.
有可能用线程(父线程等待子线程)吗?还是我必须使用别的东西?

解决方法

我建议使用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);
            }
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读