Skip to content

Instantly share code, notes, and snippets.

@SergeyTeplyakov
Last active August 29, 2015 14:06
Show Gist options
  • Save SergeyTeplyakov/a4d4df67748d27497848 to your computer and use it in GitHub Desktop.
Save SergeyTeplyakov/a4d4df67748d27497848 to your computer and use it in GitHub Desktop.
Async Programming Guidelines
using System.Threading.Tasks;
using System;
class NamingConventions
{
public static async Task DoStuffAsync()
{
await Task.Delay();
}
public static Task DoAnotherStuffAsync()
{
return Task.Run(() => {Console.WriteLine("Inside the task!")});
}
public static async Task AsyncDoStuff()
{
await Task.Delay();
}
}
// Do not use async-void methods
class AsyncVoid
{
private static async void CrazyMethod()
{
throw new Exception("Ooops!");
}
public static void Run()
{
// This code will crash an application!
CrazyMethod();
Console.ReadLine();
}
}
class PreconditionCheck
{
public static async Task AsyncMethod(string path)
{
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
await Task.Delay(100);
}
public static Task ProperAsyncMethod(string path)
{
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
return ProperAsyncMethodCore(path);
}
private static async Task ProperAsyncMethodCore(string path)
{
await Task.Delay(10);
}
public static void Run()
{
Task task = null;
try
{
task = AsyncMethod(null);
}
catch(Exception e)
{
Console.WriteLine("Can't start a task! " + e); //1
}
try
{
task.Wait();
}
catch(Exception e)
{
Console.WriteLine("Task failed! " + e); // 2
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment