示例
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>.Factory.StartNew(() =>
{
return upCounter.CountUp(maxNo);
}).ContinueWith((antecedent) =>
{
if (antecedent.Status == TaskStatus.RanToCompletion)
{
Console.WriteLine($"\nt1: {antecedent.Result}");
}
else if (antecedent.Status == TaskStatus.Faulted)
{
Console.WriteLine($"Exception occurred: {antecedent.Exception?.InnerExceptions.First().Message}");
}
});
Task<SumData>.Factory.StartNew(() =>
{
return downCounter.CountDown(maxNo);
}).ContinueWith((antecedent) =>
{
Console.WriteLine($"\nt2: {antecedent.Result.Sum}");
});
Console.WriteLine("All tasks are 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.");
throw new Exception("Unable to generate sum in Count-Up method.");
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; }
}
}