长时间暂停的并行任务 [英] Parallel tasks with a long pause

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

问题描述

我有一个类似

   private void DoSomethingToFeed(IFeed feed)
   {
      feed.SendData(); // Send data to remote server
      Thread.Sleep(1000 * 60 * 5); // Sleep 5 minutes
      feed.GetResults(); // Get data from remote server after it's processed it
   }

我想对此进行并行化,因为我有很多彼此独立的提要.根据此答案,将Thread.Sleep()留在其中并不是一个好主意.我还想等待所有线程旋转起来,直到它们都有机会获得结果.

I want to parallelize this, since I have lots of feeds that are all independent of each other. Based on this answer, leaving the Thread.Sleep() in there is not a good idea. I also want to wait after all the threads have spun up, until they've all had a chance to get their results.

处理这种情况的最佳方法是什么?

What's the best way to handle a scenario like this?

编辑,因为我无意中忽略了它:我本来考虑将此函数称为Parallel.ForEach(feeds, DoSomethingToFeed),但是我想知道找到答案后是否有更好的方法来处理睡眠我链接到了.

Edit, because I accidentally left it out: I had originally considered calling this function as Parallel.ForEach(feeds, DoSomethingToFeed), but I was wondering if there was a better way to handle the sleeping when I found the answer I linked to.

推荐答案

除非您有很多线程,否则可以保持简单.创建所有线程.您将获得一些线程创建开销,但是由于线程基本上一直处于休眠状态,因此不会有太多的上下文切换.

Unless you have an awful lot of threads, you can keep it simple. Create all the threads. You'll get some thread creation overhead, but since the threads are basically sleeping the whole time, you won't get too much context switching.

比其他任何解决方案都更容易编码(除非您使用的是C#5).因此,从此开始,并仅在实际遇到性能问题时对其进行改进.

It'll be easier to code than any other solution (unless you're using C# 5). So start with that, and improve it only if you actually see a performance problem.

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

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