示例
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<SumData> 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($"\nt1: {t1.Result}");
Console.WriteLine($"\nt2: {t2.Result.Sum}");
//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; }
}
}