示例
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;
//Create CancellationTokenSource class object (used to cancel a task)
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
Task.Run(() =>
{
return upCounter.CountUp(maxNo, cancellationTokenSource.Token);
}, cancellationTokenSource.Token).ContinueWith((antecedent) =>
{
if (antecedent.Status == TaskStatus.Canceled)
{
Console.WriteLine("Count-Up Task Cancelled.");
return -3;
}
if (antecedent.Status == TaskStatus.Faulted)
{
Console.WriteLine($"Exception occurred: {antecedent.Exception?.InnerExceptions.First().Message}");
return -1;
}
else if (antecedent.Status == TaskStatus.RanToCompletion)
{
return antecedent.Result;
}
else
{
return -2;
}
}).ContinueWith((antecedent) =>
{
Console.WriteLine($"\nt1: {antecedent.Result}");
});
Task<SumData>.Factory.StartNew(() =>
{
return downCounter.CountDown(maxNo);
}).ContinueWith((antecedent) =>
{
Console.WriteLine($"\nt2: {antecedent.Result.Sum}");
});
//Cance the t1
Task.Delay(1).Wait();
cancellationTokenSource.Cancel();
Console.WriteLine("All tasks are completed.");
Console.ReadKey();
}
}
class UpCounter
{
public long CountUp(int count, CancellationToken cancellationToken)
{
long sum = 0;
Console.WriteLine("\nCount-Up starts.");
for (int i = 1; i <= count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
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; }
}
}