Utilisation du chronomètre avec les méthodes asynchrones

J’ai du code comme suit:

public void Start() { var watch = new Stopwatch(); watch.Start(); Task.Factory.StartNew(MyMethod1); Task.Factory.StartNew(MyMethod2); watch.Stop(); Log(watch.ElapsedMilliseconds); Task.Factory.StartNew(MyMethod3); } 

Parce que MyMethod1 et MyMethod2 sont appelés de manière asynchrone, watch.Stop () est appelé au mauvais moment. Comment puis-je m’assurer que .Stop est appelé et enregistré après la fin de MyMethod1 et MyMethod2 MAIS pour m’assurer que MyMethod3 n’a pas à attendre.

Je souhaite conserver toutes les fonctionnalités du chronomètre dans ma méthode Start () et ne pas avoir de journalisation dans l’une de mes 3 méthodes, à savoir MyMethod1, MyMethod2 et MyMethod3.

Vous pouvez utiliser la méthode Task.Factory.ContinueWhenAll .

 watch.Start(); var t1 = Task.Factory.StartNew(MyMethod1); var t2 = Task.Factory.StartNew(MyMethod2); Task.Factory.ContinueWhenAll(new [] {t1, t2}, tasks => watch.Stop()); 

Si vous ciblez pour .NET 4.5 et Task.WhenAll supérieures, vous pouvez également utiliser la méthode Task.WhenAll . Il renvoie une tâche qui se terminera lorsque tous les objects de tâche transmis seront terminés.

 Task.WhenAll(t1, t2).ContinueWith(t => watch.Stop()); 

Vous devez créer un nouveau thread qui gérera le problème de journalisation. Ce thread de journalisation attendra sur EventWaitHandle.WaitAll(threadsEventWaitHandles) qui contiendra tous les threads EventWaitHandles. Quelque chose comme ca :

 private void LoggingThread() { var watch = new Stopwatch(); watch.Start(); EventWaitHandle.WaitAll(threadsEventWaitHandles); watch.Stop(); Log(watch.ElapsedMilliseconds); } 

Et aussi les méthodes MyMethod1, MyMethod2 signaleront au thread de journalisation quand elles auront fini. Quelque chose comme ca :

 private void MyMethod1() { //... your code EventWaitHandle.Set(); } private void MyMethod2() { //... your code EventWaitHandle.Set(); } 

Vous pouvez ainsi vous assurer que MyMethod3 n’a pas à attendre.

  public void Start() { var watch = new Stopwatch(); watch.Start(); Task.Factory.StartNew(MyMethod1); Task.Factory.StartNew(MyMethod2); Task.WaitAll(); // Wait for previous tasks to finish watch.Stop(); Log(watch.ElapsedMilliseconds); Task.Factory.StartNew(MyMethod3); }