我使用此代码并收到错误“方法“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>>
,我会出错。
谁能解释错误的原因。谢谢