示例
Program.cs
using System.Diagnostics;
namespace TaskExample
{
internal class Program
{
static void Main(string[] args)
{
UpCounter upCounter = new UpCounter();
DownCounter downCounter = new DownCounter();
int maxNo = 100;
Task<long> t1 = Task<long>.Factory.StartNew(() =>
{
return upCounter.CountUp(maxNo);
});
Task continuationt1 = t1.ContinueWith((antecedent) =>
{
Console.WriteLine($"\nt1: {t1.Result}");
});
Task<SumData> t2 = Task.Factory.StartNew(() =>
{
return downCounter.CountDown(maxNo);
});
Task continuationt2 = t2.ContinueWith((antecedent) =>
{
Console.WriteLine($"\nt2: {t2.Result.Sum}");
});
//Task.WaitAll(continuationt1, continuationt2);
//SumData sumData = t2.Result;
//Console.WriteLine($"t2: {sumData.Sum}");
Console.WriteLine("t1 and t2 completed.");
Console.ReadKey();
}
}
class UpCounter
{
public long CountUp(int count)
{
long sum = 0;
Console.WriteLine("\nCount-Up starts.");
for (int i = 1; i <= count; i++)
{
Console.Write($"Up: {i}, ");
sum += i;
//Task.Delay(300).Wait(); //Create a new task, and the new task pause the current task by wait method
}
Console.WriteLine("\nCount-Up ends.");
return sum;
}
}
class DownCounter
{
public SumData CountDown(int count)
{
long sum = 0;
Console.WriteLine("\nCount-Down starts.");
for (int i = count; i >= 1; i--)
{
Console.Write($"Down: {i}, ");
sum += i;
//Task.Delay(300).Wait(); //Create a new task, and the new task pause the current task by wait method
}
Console.WriteLine("\nCount-Down ends.");
return new SumData() { Sum = sum };
}
}
class SumData
{
public long Sum { get; set; }
}
}
标签:Task,Console,Sum,ContinueWith,t2,383,WriteLine,new
From: https://blog.csdn.net/KevinHuang2088/article/details/141171178