Skip to content

Instantly share code, notes, and snippets.

@StephenCleary
Forked from davidfowl/async.cs
Last active February 9, 2017 11:54
Show Gist options
  • Save StephenCleary/d5687f9d11947b7a8e3313c9fb2777bd to your computer and use it in GitHub Desktop.
Save StephenCleary/d5687f9d11947b7a8e3313c9fb2777bd to your computer and use it in GitHub Desktop.
Async quiz: How many threads are used? What does it print?
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
// The more evil version. :)
class Program
{
static void Main(string[] args)
{
var startWorkTcs = new TaskCompletionSource<object>();
var workDoneTcs = new TaskCompletionSource<object>();
var workTask = SomethingAsync(startWorkTcs, workDoneTcs);
var waiter = DoWait(workDoneTcs, workTask);
// Pre-work output.
Console.WriteLine("Hello");
// Start the work.
startWorkTcs.TrySetResult(null);
// Post-work output.
Console.WriteLine("World");
// Wait for the work to complete.
waiter.Wait();
}
static async Task DoWait(TaskCompletionSource<object> workDoneTcs, Task workTask)
{
// Asynchronously wait for the work to report that it's done.
await workDoneTcs.Task;
// Now wait for the actual work task to complete.
workTask.Wait();
}
private static async Task SomethingAsync(TaskCompletionSource<object> startWorkTcs, TaskCompletionSource<object> workDoneTcs)
{
// Asynchronously wait for the signal to start work.
await startWorkTcs.Task;
// Do the work.
Console.WriteLine("Beautiful");
// Notify caller that the work is done.
workDoneTcs.TrySetResult(null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment