Is the code from this page really the best way to simulate a long running task?
The console app I've worked up is fairly simple and seems to work just fine.
I'm not sure if I could swap out DoExpensiveCalculation
for an an Async
method, like GetStringAsync
from HttpClient
without issue.
using System;
using System.Threading.Tasks;
namespace ExpensiveAsync
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("started");
var t = CalculateResult("stuff and that");
Console.WriteLine("press return");
Console.ReadLine();
}
public static async Task<string> CalculateResult(string data)
{
// This queues up the work on the threadpool.
var expensiveResultTask = Task.Run(() => DoExpensiveCalculation(data));
// Note that at this point, you can do some other work concurrently,
// as CalculateResult() is still executing!
Console.WriteLine("concurrent");
// Execution of CalculateResult is yielded here!
var result = await expensiveResultTask; // CalculateResult returns the Task object here
Console.WriteLine("synchronous"); // this code runs once the DoExpensiveCalculation method has finished
return result;
}
public static string DoExpensiveCalculation(string data)
{
var completionTime = DateTime.Now.AddSeconds(3);
Console.WriteLine("begin");
while (DateTime.Now < completionTime) ;
Console.WriteLine("finish");
return data;
}
}
}