简体   繁体   English

在间隔异步中并行运行一些函数?

[英]Run some functions parallel in an interval async?

I have a Timer and Im calling some functions in an interval. 我有一个Timer和Im在一个间隔中调用一些函数。 Right now I have something like this: 现在我有这样的事情:

private System.Timers.Timer timer;
private int sync;

void Start()
{
  timer = new System.Timers.Timer(interval);
  timer.Elapsed += new ElapsedEventHandler(Elapsed);
  timer.Enabled = true;
}

void Elapsed(object s, ElapsedEventArgs e)
{
  if (System.Threading.Interlocked.CompareExchange(ref sync, 1, 0) == 0)
  {
    Parallel.Invoke( () => Function1(), () => Function2(), () => Function3(),
                     () => Function4() );
  }
  sync = 0;
}

This is not bad. 这不错。 I can start the functions parallel AND one function cannot run 2+ times, just once (this is how I want it). 我可以并行启动函数,一个函数不能运行2次以上,只需一次(这就是我想要的)。 The problem is: lets say function4() takes longer then my interval , so the other functions have to wait too. 问题是:假设function4()我的interval花费的时间更长,所以其他函数也必须等待。 If I remove the sync there, the other functions wont wait BUT another function4() call could start in another thread - and I dont want that one functions is running twice. 如果我在那里删除sync ,其他函数不会等待但另一个function4()调用可以在另一个线程中启动 - 我不希望一个函数运行两次。 Any suggestions? 有什么建议? Thank you 谢谢

You would have to keep track of each function individually so you have control on which functions you can initiate right away and which ones you need to wait on eg 您必须单独跟踪每个功能,以便您可以控制可立即启动的功能以及需要等待的功能,例如:

private AutoResetEvent f1 = new AutoResetEvent(true);
private AutoResetEvent f2 = new AutoResetEvent(true);
...

void Elapsed(object s, ElapsedEventArgs e)
{
    ...
    Parallel.Invoke(() => { f1.WaitOne(); Function1(); f1.Set(); },
                    () => { f2.WaitOne(); Function2(); f2.Set(); }
                    ...
    ...
}

Something like this would block any functions that are already executing and allow other ones to start which aren't. 这样的东西会阻止任何已经执行的函数,并允许其他函数启动而不是。

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

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