using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (var cts = new CancellationTokenSource())
{
var task1 = Task.Run(() => CalculatePiSeries1(cts.Token, 3.1415926535898));
var task2 = Task.Run(() => CalculatePiSeries2(cts.Token, 3.1415926535898));
Task completedTask = await Task.WhenAny(task1, task2);
cts.Cancel();
if (completedTask == task1)
{
var result1 = await task1;
Console.WriteLine("Series 1 completed faster with result: " + result1);
}
else if (completedTask == task2)
{
var result2 = await task2;
Console.WriteLine("Series 2 completed faster with result: " + result2);
}
try
{
await Task.WhenAll(task1, task2);
}
catch (OperationCanceledException) { }
}
Console.ReadLine();
}
static async Task<(double result, Stopwatch sw)> CalculatePiSeries1(CancellationToken token, double targetPi)
{
Stopwatch sw = Stopwatch.StartNew();
double pi = 0;
double term = 1;
int i = 0;
while (true)
{
if (token.IsCancellationRequested) break;
if (i % 2 == 0)
{
pi += term;
}
else
{
pi -= term;
}
term = 1.0 / (2 * i + 1);
i++;
if (Math.Abs(pi * 4 - targetPi) < Math.Pow(10, -10))
{
sw.Stop();
return (pi * 4, sw);
}
}
sw.Stop();
return (pi * 4, sw);
}
static async Task<(double result, Stopwatch sw)> CalculatePiSeries2(CancellationToken token, double targetPi)
{
Stopwatch sw = Stopwatch.StartNew();
double piSquared = 0;
int i = 0;
while (true)
{
if (token.IsCancellationRequested) break;
piSquared += 1.0 / Math.Pow(2 * i + 1, 2);
i++;
double pi = Math.Sqrt(8*piSquared);
if (Math.Abs(pi * pi - targetPi*targetPi) < Math.Pow(10, -10))
{
sw.Stop();
return (pi, sw);
}
}
sw.Stop();
return (Math.Sqrt(8*piSquared), sw);
}
}