Since Task-based Asynchronous Pattern is now the recommended route (per MSDN @ here and here), how would I go about converting the simple hello world code below into a Task-based Asynchronous Pattern?
Lets assume I don’t know anything about Tasks and I’ve tried to demo input to and output from the worker as well as calling from the ‘main’.
class Program
{
static void Main(string[] args)
{
Worker wk = new Worker();
string result = wk.DoWork(1000);
Console.WriteLine(result);
Console.WriteLine("Main says, Hello World!");
Console.ReadLine();
}
}
class Worker
{
public string DoWork(int delay)
{
Console.WriteLine("Worker says, working ...");
Thread.Sleep(delay); // represents the 100ms+ workload
return "Worker says, I'm done! Hello World!";
}
}
This depends on what exactly do you want to make asynchronous. If the
Thread.Sleep()represents some CPU-bound work, then you’re not going to gain much from using TAP.If you want to make the wait inside
DoWork()asynchronous, that means changing the signature fromstringtoasync Task<string>and then usingawait Task.Delay()instead ofThread.Sleep().If you also want to make
Main()asynchronous, you can, if you’re using C# 7.1 or newer.If you’re using an older version of C#, then it becomes. What you can do is to create asynchronous
MainAsync()and then synchronouslyWait()for that in the realMain(). This means the main thread would be blocked, but we kind of need that to keep the application alive. Also, mixing asynchronousawaitwith synchronousWait()is usually not a good idea (especially since it often leads to deadlocks), but in this case it’s okay.If we make
Main()asynchronous, it would be nice to make the blockingReadLine()asynchronous too. There is noConsole.ReadLineAsync(), but we can useConsole.Infor that.So, the final code would look like this: