I have method that calculates pi. I was just wonder if I could make this faster using C#5’s async/await features?
public decimal CalculatePi(int measure)
{
var target = measure;
decimal current = 3;
var incrementing = false;
var inner = (decimal)1.0;
while (current < target)
{
if (!incrementing)
{
inner = inner - (1/current);
current += 2;
incrementing = true;
}
if (incrementing)
{
inner = inner + (1/current);
current += 2;
incrementing = false;
}
}
return 4*inner;
}
Async and await are best used when accessing other resources like the network or the hard drive where speeds might be slower than you want. Using it on purely processor code like this will only make your code share the processor with the rest of your code (the original calling code that started this method) much like starting a thread. Either it’s slowed down by your other code continuing to do things, or that other code hits await and continues as if it were synchronous. There would be no major benefit to using async/await.