Created
October 7, 2014 09:06
-
-
Save iarovyi/d9135e621f156c31f5ea to your computer and use it in GitHub Desktop.
CustomTaskConsoleApplication
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.Runtime.CompilerServices; | |
using System.Threading; | |
namespace CustomTaskConsoleApplication | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Task job = AsyncMethod(); | |
Console.WriteLine("Do some job"); | |
Console.WriteLine("Main thread is waiting..."); | |
Task.WaitAny(job); | |
Console.ReadKey(); | |
} | |
public static async Task AsyncMethod() | |
{ | |
Console.WriteLine("Sync part of async method"); | |
await new Promise(()=> Thread.Sleep(3000)); | |
Console.WriteLine("Continuation"); | |
} | |
} | |
#region CustomAwaiter - Stupid and simplest awaiter implementation | |
public class CustomAwaiter : ICriticalNotifyCompletion | |
{ | |
private readonly Promise _promise; | |
public CustomAwaiter(Promise promise) | |
{ | |
_promise = promise; | |
} | |
public bool IsCompleted | |
{ | |
get { return _promise.IsCompleted; } | |
} | |
public void OnCompleted(Action continuation) | |
{ | |
_promise.ContinueWith(continuation); | |
} | |
public void UnsafeOnCompleted(Action continuation) | |
{ | |
OnCompleted(continuation); | |
} | |
public void GetResult() | |
{ | |
_promise.Wait(); | |
} | |
} | |
#endregion | |
#region Promise - Stupid and simplest Task implementation | |
public class Promise | |
{ | |
private Action _continuation; | |
public Promise(Action action) | |
{ | |
ThreadPool.QueueUserWorkItem((o) => | |
{ | |
action(); | |
IsCompleted = true; | |
_continuation(); | |
}); | |
} | |
public bool IsCompleted { private set; get; } | |
public CustomAwaiter GetAwaiter() | |
{ | |
return new CustomAwaiter(this); | |
} | |
public void ContinueWith(Action continuation) | |
{ | |
_continuation = continuation; | |
} | |
public void Wait() | |
{ | |
if (!IsCompleted) | |
{ | |
SpinWait.SpinUntil(() => IsCompleted); | |
} | |
} | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment