Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcomartin/12fe98b3cd40d332c5ff to your computer and use it in GitHub Desktop.
Save dcomartin/12fe98b3cd40d332c5ff to your computer and use it in GitHub Desktop.
Demo-AsyncException
using System;
using System.Threading.Tasks;
namespace dcomartin.Demo.AsyncAwaitExceptions
{
class Program
{
static void Main(string[] args)
{
// Since main entry does not support async, lets create a async task.
Task.Run(async () =>
{
var demo = new AsyncDemo();
// Exception thrown will be swallowed
demo.MethodCalledWithoutAwait();
// Exception will be raised
await demo.MethodCalledWithAwait();
}).Wait();
}
}
public class AsyncDemo
{
public void MethodCalledWithoutAwait()
{
// Although this method throws an exception, because we are not awaiting it,
// it will be swallowed and will not be caught.
AsyncMethodException();
}
public async Task MethodCalledWithAwait()
{
// Because we are awaiting the async method, the exception thrown will be raised.
await AsyncMethodException();
}
public async Task AsyncMethodException()
{
// This method would do some async call (possible IO).
// For the example, we will throw an exception to show as an example how\
// the exception will be swollowed by not calling await.
throw new InvalidOperationException("");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment