Last active
August 29, 2015 14:06
-
-
Save SergeyTeplyakov/a4d4df67748d27497848 to your computer and use it in GitHub Desktop.
Async Programming Guidelines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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