Skip to content

Instantly share code, notes, and snippets.

@StephenCleary StephenCleary/async.cs

forked from davidfowl/async.cs
Last active Feb 9, 2017
Embed
What would you like to do?
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
You can’t perform that action at this time.