Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async as a method result manager?

Tags:

c#

async-await

From here :

The “async” keyword enables the “await” keyword in that method and changes how method results are handled. That’s all the async keyword does!

The second part got me interesting , but I didn't find explanation to this in the article.

Doing a little test ( notice - no awaited tasks are here) :

  static void X()
    {
        try
        {
            Y();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    static async void Y() //<---- notice here
    {
        throw new NotImplementedException();
    }


    static void Main(string[] args)
    {
        X();

        Console.ReadLine();
    }

This will terminate the program :

enter image description here

While removing async from this :

 static async void Y()  
    {
        throw new NotImplementedException();
    }

Will yield :

enter image description here

MSDN says nothing about it :

If the method that the async keyword modifies doesn't contain an await expression or statement, the method executes synchronously. A compiler warning alerts you to any async methods that don't contain await, because that situation might indicate an error

Question

If so , what else does the word async does that my code yields different results ?

like image 354
Royi Namir Avatar asked Mar 17 '23 08:03

Royi Namir


1 Answers

async methods catch all exceptions, don't throw them up the stack to the caller of the method, and instead include them in the Task returned from the method, marking it as a faulted Task. If the method is async void, the error is thrown at an application level, as you have seen, since there is no way to observe the exception through a Task.

like image 104
Servy Avatar answered Mar 27 '23 17:03

Servy