使用与异步方法秒表 [英] Using the Stopwatch with Async methods
问题描述
我有一些code如下:
I have some code as follows:
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);
}
由于MyMethod1和MyMethod2被称为异步watch.Stop()被调用在错误的时间。我怎样才能确保.Stop被调用和MyMethod1和MyMethod2结束后记录但确保MyMethod3不必等待。
Because MyMethod1 and MyMethod2 are called Asynchronously watch.Stop() gets called at the wrong time. How I can ensure that .Stop gets called and logged after MyMethod1 and MyMethod2 finish BUT ensure that MyMethod3 does not have to wait.
我要保留所有的秒表功能,在我的start()方法,并没有记录在我的任何3种方法,即MyMethod1,MyMethod2和MyMethod3
I want to keep all Stopwatch functionality in my Start() method and not have the logging in any of my 3 methods i.e. MyMethod1, MyMethod2 and MyMethod3
推荐答案
您可以使用 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());
如果你的目标为.NET 4.5和上,你也可以使用该方法 Task.WhenAll
。它返回一个任务将完成,当所有的传递任务的对象已经完成。
If you're targeting for .NET 4.5 and upper, you can also use the method Task.WhenAll
. It returns a task that will complete when all of the passed Task objects have completed.
Task.WhenAll(t1, t2).ContinueWith(t => watch.Stop());
这篇关于使用与异步方法秒表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!