'Is the async keyword required to create asynchronous functionality? Did this functionality change in the recent past?
I'm attempting to show that it is possible for my team to add asynchronous functionality to a currently "fully-syncrhonous" program. Are there any reasons, such as requiring the async decorator, that the following code would not yield expected results if something similar were shoved into our production code?
Code:
static void Main(string[] args)
{
//TODO: Try to show that Tasks are async inside of sync methods
var waitForStuff = Task.Run(() => stuff());
Thread.Sleep(1000);
Console.WriteLine("In between stuff- From Main");
//waitForStuff.Wait(); - This wait doesn't even appear to be necessary
var result = waitForStuff.Result;
if (result == null)
{
result = "Main didn't wait for task";
}
Console.WriteLine(result);
}
private static string stuff(){
Console.WriteLine("Beginning of Stuff");
Thread.Sleep(5000);
Console.WriteLine("End of Stuff");
return "stuff";
}
Console:
Beginning of Stuff
In between stuff- From Main
End of Stuff
stuff
Solution 1:[1]
What do you mean by "asynchronous functionality" and "expected results"?
Your code waits for the result of a non-async method because the type it's returning (Task) is awaitable. But it isn't using the normal task asynchronous pattern and the async / await keywords.
The async keyword applied to a method enables the await keyword in that method. Then the await keyword examines the awaitable (eg Task) argument. If the awaitable has completed, the method just runs synchronously. If the awaitable hasn't completed, the method returns immediately but tells the awaitable to run the rest of the method after task completion.
So in your context:
var waitForStuff = Stuff();
public async Task<string> Stuff()
{
Console.WriteLine("Beginning of Stuff");
await Task.Delay(5000);
Console.WriteLine("End of Stuff");
return "stuff";
}
You should be aware of how to use async/await properly in console programs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
