简体   繁体   English

任务并行库执行长时间运行的操作

[英]Task Parallel Library to perform long running operations

Is it a good approach to use Task (Task Parallel Library) to perform long running operations (sometimes can take few hours to complete)? 使用Task(任务并行库)执行长时间运行的操作(有时可能需要几个小时才能完成)是一种好方法吗?

In one of the stack overflow threads I saw one person telling not to use Threadpool if the long running operations take more than few seconds to complete. 在一个堆栈溢出线程中,我看到一个人告诉如果长时间运行的操作需要花费几秒钟才能完成,则不要使用Threadpool。 I have such a doubt since Task also uses the ThreadPool under the hood, in order to distribute the work, without going through the overhead of Thread creation/or un-necessary context switching. 我很怀疑,因为Task还在后台使用了ThreadPool来分发工作,而不会经历线程创建/不必要的上下文切换的开销。

As long as you keep a foreground thread alive, using a task is OK - just be sure to specify the TaskCreationOptions.LongRunning option to prevent thread starvation if you are running a lot of concurrent tasks. 只要使前台线程保持活动状态,就可以使用任务-只要运行大量并发任务,请确保指定TaskCreationOptions.LongRunning选项以防止线程饥饿。

The below simple console application demonstrates how the lack of a foreground thread will terminate the "long running thread" prematurely as the process ends. 下面的简单控制台应用程序演示了缺少前台线程将如何在进程结束时过早地终止“长时间运行的线程”。

class Program
{
    static void Main( string[] args )
    {
        Task.Factory.StartNew( () =>
            {
                Console.WriteLine( "Before sleep" );
                System.Threading.Thread.Sleep( 5000 );
                Console.WriteLine( "After sleep" );
            }
            , TaskCreationOptions.LongRunning
            );

        // press a key prior to the 5 second sleep expiration to demonstrate early termination
        Console.ReadKey();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM