Skip to content

Instantly share code, notes, and snippets.

@svick
Created April 20, 2018 16:45
Show Gist options
  • Select an option

  • Save svick/438cb96f15ccb0ec8d8dd82038da8764 to your computer and use it in GitHub Desktop.

Select an option

Save svick/438cb96f15ccb0ec8d8dd82038da8764 to your computer and use it in GitHub Desktop.
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