Created
February 13, 2018 10:19
-
-
Save ankitbko/de9ae09c0255611b1fcaca8dc9ff370f to your computer and use it in GitHub Desktop.
Two faces of async/await
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; | |
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