在不同时间执行并行任务 [英] Parallel task execution at different time

查看:52
本文介绍了在不同时间执行并行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我有控制台应用程序并行执行几项任务。在我的情况下,重要的是我希望任务同时完成。我知道每项任务要花多长时间。因此,我们的想法是以某种方式延迟Parallel.ForEach
中的每个任务,并且每个任务都有自定义时间延迟,因此它们都在同一时间完成,最后所有任务将大致同时完成所有任务。花费大部分时间。

I have console app which performs a couple of tasks in parallel. In my case the important part is that i want the tasks to complete at the same time. I know how long each task is going to take. So the idea is to delay somehow every task in the Parallel.ForEach with custom time delay per task so they all finish at the same time and in the end all the tasks will complete approximately at the same time as the one which takes most time.

示例:

interface IService
{
    void DoWork();
}

class Program
{
    static void Main(string[] args)
    {
        var services = new List<IService>();
        services.Add(new ServiceA());//Takes 500ms to DoWork()
        services.Add(new ServiceB());//Takes 1000ms to DoWork()
        services.Add(new ServiceC());//Takes 5000ms to DoWork()

        Parallel.ForEach(services, z =>
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            z.DoWork();
            Console.WriteLine($"Ready for {sw.Elapsed}");
        });
    }
}

输出:

Ready for 00:00:00.5006837
Ready for 00:00:01.0002284
Ready for 00:00:05.0010202
Press any key to continue . . .

如何修改代码使输出如下:

How to modify the code so the output will look like:

Ready for 00:00:05.5006837
Ready for 00:00:05.0002284
Ready for 00:00:05.0010202
Press any key to continue . . .

我想最明显的解决方案是区分哪个服务是循环中的z并在调用z.DoWork()之前添加自定义Thread.Sleep,但我正在寻找更智能的解决方案。

I guess the most obvious solution would be to distinguish which Service is z in the loop and add custom Thread.Sleep before calling z.DoWork(), but I am looking for smarter solution.




推荐答案



我想你在考虑为什么不将所有三个服务的启动代码移动到另一个线程,他们可以立即返回?

I think you're thinking it backwards. Why not move startup code of all three service to another threadso they can return immediately?


这篇关于在不同时间执行并行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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