public class TestAsync{ private static string result; static void Main() { PrintAsync(); Console.WriteLine(result); } static async Task<string> PrintAsync() { await Task.Delay(5); result = "Hello world!"; return "This is example"; }}
public class TestAsync
{
private static string result;
static void Main()
PrintAsync();
Console.WriteLine(result);
}
static async Task<string> PrintAsync()
await Task.Delay(5);
result = "Hello world!";
return "This is example";
Above code snippet will not return any result because of async method call without await.
if you are expeting to execute then you can call in two ways,
var r = PrintAsync().Result;
Another way you have to call with await keyword then will return result as “Hello world!”
This will not show any result on the screen.I agree with Jignesh
Just to add we can also add the async and Task keyword into the Main method so we can add the asyncbefore the PrintAsync method. Although this is supported starting at C# 7.1.
async
Task
Main
PrintAsync
static async Task Main(string[] args){ var r = await PrintAsync(); Console.WriteLine(r); //This is example Console.WriteLine(result); //Hello World Console.ReadLine();}
static async Task Main(string[] args)
var r = await PrintAsync();
Console.WriteLine(r); //This is example
Console.WriteLine(result); //Hello World
Console.ReadLine();
Hope this helps. Thanks.
This program will not return any result because of async method call without using of await.
In the Main() method, PrintAsync() is called, but since it is an asynchronous method, it returns immediately before its task is complete. The Console.WriteLine(result) statement executes and prints the current value of result, which is still null because the task returned by PrintAsync() hasn’t finished yet.
When the task finally completes after the 5 millisecond delay, it sets the value of result to “Hello world!”, but this happens after the Console.WriteLine(result) statement has already executed. Therefore, the output of the program is null.
The output of this program will be null