0

Many of the tutorials I've read on async/await feel like they complicate the concept way too much. Ideally, it would allow some time consuming task to be run in the background while the calling method continues its business.

I decided to create the simplest example of async/await I can think of. C# console application:

class Program
{
    static void Main(string[] args)
    {

        PrintTwoTimes();

        Console.WriteLine("Main Method!");

        Console.ReadLine();
    }

    async static Task PrintTwoTimes()
    {
        await Task.Run(() =>
        {
            Thread.Sleep(500);
            Console.WriteLine("Inside Async Task!");
        });

        Console.WriteLine("After Async Task!");
    }
}

The output is as I expected.

Output

The calling thread continues its execution without waiting for PrintTwoTimes() to complete.

What I'd like to know is what is dangerous about such a simple approach to async/await, as I have done, in the real world?

* EDIT *

After being told my question is idiotic, I am removing the bit about static and adding updated code that removes it

class Program
{
    static void Main(string[] args)
    {
        //call the async thread
        var prtclss = new PrintClass();

        prtclss.PrintTwoTimes();

        Console.WriteLine("Main Method!");

        Console.ReadLine();
    }


}

class PrintClass
{
    public string str1 { get; set; }
    public string str2 { get; set; }

    public PrintClass()
    {
        str1 = "Inside Async Task!";
        str2 = "After Async Task!";
    }

    public async Task PrintTwoTimes()
    {
        await Task.Run(() =>
        {
            //simulate time consuming task
            Thread.Sleep(500);
            Console.WriteLine(str1);
        });

        Console.WriteLine(str2);

    }


}
Moe45673
  • 854
  • 10
  • 20
  • https://www.bing.com/search?q=c%23+console+async should give you sample that at least works correctly... Asking multiple questions per post is wrong as it makes very hard to close as duplicate or provide concrete answer... And definitely second question which is essentially "why I can't call instance method from static method" calls for some negative attention. – Alexei Levenkov Dec 08 '16 at 18:14
  • Indeed. I am going to edit my question to remove the "static" – Moe45673 Dec 08 '16 at 18:18
  • 3
    The "dangerous" part is that you never wait for PrintTwoTimes() to complete. It happens to work anyway as long as you don't press Enter too quickly. – piedar Dec 08 '16 at 18:22
  • 1
    @piedar - that is already explained in answers found by search I've posted above (http://stackoverflow.com/questions/3840795/console-app-terminating-before-async-call-completion or http://stackoverflow.com/questions/9208921/cant-specify-the-async-modifier-on-the-main-method-of-a-console-app), so OP should have seen it already... Still good idea to re-iterate. – Alexei Levenkov Dec 08 '16 at 18:26

0 Answers0