示例
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<long> t2 = Task.Factory.StartNew(() =>
{
return downCounter.CountDown(maxNo);
});
//t1.Wait(); //Need to be waited for
//t2.Wait(); //Need to be waited for
//Task.WaitAll(new Task[] { t1, t2 });
Task.WaitAll(t1, t2);
Console.WriteLine($"t1: {t1.Result}");
Console.WriteLine($"t2: {t2.Result}");
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;
}
Console.WriteLine("\nCount-Up ends.");
return sum;
}
}
class DownCounter
{
public long CountDown(int count)
{
long sum = 0;
Console.WriteLine("\nCount-Down starts.");
for (int i = count; i >= 1; i--)
{
Console.Write($"Down: {i}, ");
sum += i;
}
Console.WriteLine("\nCount-Down ends.");
return sum;
}
}
}
标签:Task,Console,Generic,sum,t2,t1,379,WriteLine
From: https://blog.csdn.net/KevinHuang2088/article/details/141169751