如何使用Task <list <t>&gt;获取项目列表任务的定义?</list <t>

时间:2012-12-13 15:12:08

标签: c# task-parallel-library

我使用此代码并获取错误“方法”doSomthing1“在当前上下文中不存在”:

static void Main( ) {
  Stopwatch stopwatch1;
  stopwatch1 = new Stopwatch( );
  stopwatch1.Reset( );
  stopwatch1.Start( );
  Task<List<int>> myTask = Task<List<int>>.Factory.StartNew( ( ) => doSomething1( ) );
  //Task<int> myTask = Task<int>.Factory.StartNew( ( ) => doSomething2 () );

  Thread.Sleep( 500 );
  Stopwatch stopwatch2 = new Stopwatch( );
  stopwatch2.Reset( );
  stopwatch2.Start( );
  //myTask.Wait( );
  if( myTask.IsCompleted ) {
    stopwatch2.Stop( );
  }

   myTask.Result.ForEach (x => Console.WriteLine (x.ToString () ));
  stopwatch1.Stop( );
  Console.WriteLine( "Stopwatch 1 elapsed time " + stopwatch1.ElapsedMilliseconds.ToString( ) );
  Console.WriteLine( "Stopwatch 2 elapsed time " + stopwatch2.ElapsedMilliseconds.ToString( ) );
  Console.Read( );
}

static List<int> doSomething1(  ) {
  Thread.Sleep( 2000 );
  return new List<int> { 1, 2, 3, 4, 5, 6 };     
}

static int doSomething2 () {
  Thread.Sleep( 2000 );
  int k = 2 ;
  return k ;
}

如果我将任务与任务定义一起使用,那么每件事都有效,但当我尝试使用Task<List<T>>时,我会收到错误。

任何人都可以解释错误的原因。感谢

1 个答案:

答案 0 :(得分:4)

区分大小写的方法名称,doh!。