在C#中高效管理线程 [英] Managing threads efficiently in C#

查看:518
本文介绍了在C#中高效管理线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,用户可以选择执行许多任务以及最大线程数.每个任务应在单独的线程上运行.这是我在寻找的东西:

I have an application in which the user will choose to do a number of tasks along with the maximum number of threads. Each task should run on a separate thread. Here is what I am looking for:

如果用户指定"n小于t",其中n是最大线程数,而t是任务数.该程序应运行"n"个线程,并在它们完成后以某种方式通知该程序并重复循环,直到所有任务都完成为止.

If the user specified "n less than t" where n is the maximum number of threads and t is the number of tasks. The program should run "n" threads and after they finish, the program should be notified by some way and repeat the loop untill all tasks are done.

我的问题是: 如何知道所有正在运行的线程都已完成工作,以便我可以重复循环.

My Question is: How to know that all running threads has finished their job so that I can repeat the loop.

推荐答案

我建议使用

I recommend using the ThreadPool for your task. Its algorithm will generally be more efficient than something you can roll by hand.

现在,所有线程完成后,有趣的部分将得到通知.除非您真的有特殊需求使该解决方案不合适,否则使用 CountdownEvent 类,这是一种特殊的等待句柄,一直等到它被发信号通知n次.这是一个示例:

Now the fun part is getting notified when all of your threads complete. Unless you have really specific needs which make this solution unsuitable, it should be easy enough to implement with the CountdownEvent class, which is a special kind of waithandle that waits until its been signaled n times. Here's an example:

using System;
using System.Linq;
using System.Threading;
using System.Diagnostics;

namespace CSharpSandbox
{
    class Program
    {
        static void SomeTask(int sleepInterval, CountdownEvent countDown)
        {
            try
            {
                // pretend this did something more profound
                Thread.Sleep(sleepInterval);
            }
            finally
            {
                // need to signal in a finally block, otherwise an exception may occur and prevent
                // this from being signaled
                countDown.Signal();
            }
        }

        static CountdownEvent StartTasks(int count)
        {
            Random rnd = new Random();

            CountdownEvent countDown = new CountdownEvent(count);

            for (int i = 0; i < count; i++)
            {
                ThreadPool.QueueUserWorkItem(_ => SomeTask(rnd.Next(100), countDown));
            }

            return countDown;
        }

        public static void Main(string[] args)
        {
            Console.WriteLine("Starting. . .");
            var stopWatch = Stopwatch.StartNew();
            using(CountdownEvent countdownEvent = StartTasks(100))
            {
                countdownEvent.Wait();
                // waits until the countdownEvent is signalled 100 times
            }
            stopWatch.Stop();
            Console.WriteLine("Done! Elapsed time: {0} milliseconds", stopWatch.Elapsed.TotalMilliseconds);
        }
    }
}

这篇关于在C#中高效管理线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆