Created
September 1, 2019 01:06
-
-
Save Fyzxs/84732646d74c379aedb3ccda156f5347 to your computer and use it in GitHub Desktop.
Example of an awaitable unstarted task
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
internal class Program | |
{ | |
private static async Task Main(string[] args) | |
{ | |
Task<string> task = new Task<string>(() => | |
{ | |
Console.WriteLine("Inside the unstarted task"); | |
return "Some Value"; | |
}); | |
SampleAsync<string> sampleAsync = new SampleAsync<string>(task); | |
Console.WriteLine("Waiting a short time..."); | |
for (int i = 0; i < int.MaxValue; i++) { } | |
string value = await sampleAsync; | |
Console.WriteLine(value); | |
Console.WriteLine("Hit enter to exit"); | |
Console.ReadLine(); | |
} | |
} | |
//This is the object that gets awaited | |
public class SampleAsync<T> | |
{ | |
private readonly Task<T> _t; | |
public SampleAsync(Task<T> t) => _t = t; | |
public TaskAwaiter<T> GetAwaiter() | |
{ | |
_t.Start(); | |
return _t.GetAwaiter(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment