Created
April 20, 2018 16:45
-
-
Save svick/438cb96f15ccb0ec8d8dd82038da8764 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
| using System.Collections.Generic; | |
| using System.Diagnostics; | |
| using System.Linq; | |
| using System.Threading.Tasks; | |
| using Microsoft.AspNetCore.Mvc; | |
| using coremvcapp.Models; | |
| using System.Net; | |
| using System.Runtime.CompilerServices; | |
| namespace coremvcapp.Controllers | |
| { | |
| public class HomeController : Controller | |
| { | |
| public IActionResult Index() | |
| { | |
| return View(); | |
| } | |
| public async Task<int> AsyncTask() | |
| { | |
| var client = new WebClient(); | |
| var content = await client.DownloadStringTaskAsync("http://google.com"); | |
| return content.Length; | |
| } | |
| public CustomAwaitable<int> CustomAwaitable() | |
| { | |
| var result = new CustomAwaitable<int>(); | |
| var client = new WebClient(); | |
| client.DownloadStringCompleted += (s, e) => result.SetResult(e.Result.Length); | |
| client.DownloadStringAsync(new Uri("http://google.com")); | |
| return result; | |
| } | |
| } | |
| public class CustomAwaitable<T> | |
| { | |
| private bool isCompleted; | |
| private T result; | |
| private readonly List<Action> completedActions = new List<Action>(); | |
| public Awaiter GetAwaiter() => new Awaiter(this); | |
| public void SetResult(T result) | |
| { | |
| this.result = result; | |
| isCompleted = true; | |
| foreach (var action in completedActions) | |
| { | |
| action(); | |
| } | |
| } | |
| public class Awaiter : INotifyCompletion | |
| { | |
| private CustomAwaitable<T> awaitable; | |
| public Awaiter(CustomAwaitable<T> awaitable) => this.awaitable = awaitable; | |
| public bool IsCompleted => awaitable.isCompleted; | |
| public void OnCompleted(Action continuation) => awaitable.completedActions.Add(continuation); | |
| public T GetResult() => awaitable.result; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment