Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of an awaitable unstarted task
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