Created by Michael Lyons
// Asynchronous Method public async Task<int> DoSomethingAsync() { await Task.Delay(2000); return 0; }
public interface IAsyncService { Task DoSomethingAsync(); // note there is no async } public class AsyncService : IAsyncService { public async Task DoSomethingAsync() // awaitable { await Task.Delay(100); } public async void DoSomethingElse() // void { await Task.Delay(100); } public async int GetIntAsync() // Compile time error { await Task.Delay(100); return 0; } }
public interface IAwaitable<T> { IAwaiter<T> GetAwaiter(); } public interface IAwaiter<T> : INotifyCompletion { bool IsCompleted { get; } void OnCompleted(Action continuation); T GetResult(); }
public async Task<int> ThrowAsync() { await ThrowsExceptionAsync(); // thrown from here var result = ShouldThrowAsync().Result; // will also throw here var task = ShouldThrowAsync(); // will throw here when // exception happens before await // ... result = task.Result; // will throw here when it happens after return 0; }
Action action = async () => await Command.ExecuteAsync(new object());
public async Task<int> DoSomethingAsync() { var tasks = Enumerable.Range(1,1000000) .GroupBy(i => i % 4) .Select(g => Task.Run(() => SomeCalc(g.ToList()))) .ToList(); var sum = 0; foreach (var task in tasks.InCompletionOrder()) { var result = await task; sum += result; } return sum; }