Skip to content

Instantly share code, notes, and snippets.

@JayBazuzi
Created August 28, 2016 20:26
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 JayBazuzi/dad5449d24e0e2f95d54781ec7d1722a to your computer and use it in GitHub Desktop.
Save JayBazuzi/dad5449d24e0e2f95d54781ec7d1722a to your computer and use it in GitHub Desktop.
Demonstrating an alternative to `async void` event handlers. Both print out messages in the order listed (1/2/3/4). Also, if you remove the Sleep(), neither prints out #4 because the process exits first.
static void Main()
{
MyEvent += Handle;
Console.WriteLine("1. Before invoking event");
MyEvent(null, null);
Console.WriteLine("3. After invoking event");
Thread.Sleep(1000);
}
private static async void Handle(object sender, EventArgs e)
{
Console.WriteLine("2. Start of handle");
await Task.Delay(500);
Console.WriteLine("4. End of handle, after await");
}
static event EventHandler MyEvent;
static void Main(string[] args)
{
MyEvent += Handle;
Console.WriteLine("1. Before invoking event");
MyEvent(null, null);
Console.WriteLine("3. After invoking event");
Thread.Sleep(1000);
}
private static void Handle(object sender, EventArgs e)
{
HandleAsync().ForgetTask();
}
private static async Task HandleAsync()
{
Console.WriteLine("2. Start of handle");
await Task.Delay(500);
Console.WriteLine("4. End of handle, after await");
}
static event EventHandler MyEvent;
}
static class TaskExtensions
{
/// <summary>
/// Suppresses warning CS4014 ("Because this call is not awaited, execution of the current method continues before the call is completed.") and makes it obvious that you didn't want to await the call.
/// </summary>
public static void ForgetTask(this Task @this)
{
}
}
static void Main()
{
MyEvent += Handle;
Console.WriteLine("1. Before invoking event");
MyEvent(null, null);
Console.WriteLine("3. After invoking event");
Thread.Sleep(1000);
}
private static void Handle(object sender, EventArgs e)
{
HandleAsync();
}
private static async Task HandleAsync()
{
Console.WriteLine("2. Start of handle");
await Task.Delay(500);
Console.WriteLine("4. End of handle, after await");
}
static event EventHandler MyEvent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment