1

在 MSDN 在线文章《How to: Wait on One or More Tasks to Complete》中,有一段代码:

// Try three different approaches to the problem. Take the first one
tasks2[0] = Task<double>.Factory.StartNew(() => TrySolution1());
tasks2[1] = Task<double>.Factory.StartNew(() => TrySolution2());
tasks2[2] = Task<double>.Factory.StartNew(() => TrySolution3());

调用 3 种不同的方法,它们的功能完全相同,具有完全相同的主体:

static double TrySolution1()
//static double TrySolution2()
//static double TrySolution3() 
{
   int i = rand.Next(1000000);
   // Simulate work by spinning
   Thread.SpinWait(i); 
   return DateTime.Now.Millisecond;
}   

我无法理解这些多重重复的实现说明了什么?

与使用一种方法有什么区别

tasks2[0] = Task<double>.Factory.StartNew(() => TrySolution1());
tasks2[1] = Task<double>.Factory.StartNew(() => TrySolution1());
tasks2[2] = Task<double>.Factory.StartNew(() => TrySolution1());

?

4

2 回答 2

3

这真的会用一种方法给你同样的答案。在这方面,这个例子是一个“糟糕的例子”。话虽如此,这只是如何解决问题的示例,而不是您将使用的“真实代码”。

I suspect the thought behind it was to show you how to use multiple, separate methods (which would normally be implemented differently, of course) and determine which finished first. I do believe the example would be more clear if a different implementation was used for each method, but the concepts being demonstrated would be identical.

于 2013-03-30T01:27:02.443 回答
1

这是如何做某事的示例。如果您尝试重构几乎所有示例代码,它将始终接近return 0;.

在这种特殊情况下,它表明如果您有几种不同的东西,您可以等待只竞争一种。忽略函数是如何实现的——这不是示例所演示的(如果它让你感到困惑——编写你自己的每个函数的不同实现)。

于 2013-03-30T01:26:51.443 回答