Skip to content

Instantly share code, notes, and snippets.

@ankitbko
Created February 13, 2018 10:19
Show Gist options
  • Save ankitbko/de9ae09c0255611b1fcaca8dc9ff370f to your computer and use it in GitHub Desktop.
Save ankitbko/de9ae09c0255611b1fcaca8dc9ff370f to your computer and use it in GitHub Desktop.
Two faces of async/await
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void Form1_Load(object sender, EventArgs e)
{
await button1;
await button2;
await button2;
MessageBox.Show("I rock");
}
}
public static class Exzt
{
public static ButtonAwaiter GetAwaiter(this Button button)
{
return new ButtonAwaiter(button);
}
}
public class ButtonAwaiter: INotifyCompletion
{
private Action _continuation;
private Button button1;
public ButtonAwaiter(Button button1)
{
this.button1 = button1;
}
public bool IsCompleted { get {return false; } }
public void OnCompleted(Action continuation)
{
button1.Click += Done;
_continuation = continuation;
}
private void Done(object sender, EventArgs e)
{
button1.Click -= Done;
_continuation();
}
public void GetResult()
{
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace AwaitMeetupDemo
{
class Program
{
static void Main(string[] args)
{
int result = Foo2().Result;
Console.WriteLine(result);
Console.ReadLine();
}
static async Task<int> Foo()
{
await Task.Delay(20000);
return 42;
}
static Task<int> Foo2()
{
var stateMachine = new StateMachine();
stateMachine.methodBuilder = new AsyncTaskMethodBuilder<int>();
stateMachine.methodBuilder.Start(ref stateMachine);
return stateMachine.methodBuilder.Task;
}
public struct StateMachine : IAsyncStateMachine
{
internal AsyncTaskMethodBuilder<int> methodBuilder;
public int state;
private TaskAwaiter awaiter;
public void MoveNext()
{
if(state == 0)
{
awaiter = Task.Delay(10000).GetAwaiter();
if(awaiter.IsCompleted)
{
state = 1;
goto state1;
}
else
{
state = 1;
methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
return;
}
}
state1:
if (state==1)
{
awaiter.GetResult();
methodBuilder.SetResult(42);
}
}
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
methodBuilder.SetStateMachine(stateMachine);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment