Search⌘ K
AI Features

Asynchronous to Synchronous Problem

Explore how to convert asynchronous execution to synchronous using C# concurrency tools. Understand how to design a solution with monitors and callback wrappers to make the main thread wait for asynchronous tasks to complete, ensuring safe and predictable execution without modifying original code.

Asynchronous to Synchronous Problem

This is an actual interview question asked at Netflix.

Imagine we have an Executor class that performs some useful task asynchronously via the method asynchronousExecution(). Additionally, the method accepts a callback object which implements the Callback interface. The passed-in callback object’s done() method gets invoked when the asynchronous execution is complete. The definition for the involved classes is below:

C#
public class Executor
{
public void asynchronousExecution(Callback callback)
{
Thread t = new Thread(() =>
{
// Simulate useful work by sleeping for 5 seconds
Thread.Sleep(5000);
callback.done();
});
t.Start();
}
}

Callback Interface and Implementation

C#
public interface ICallback
{
void done();
}
public class Callback : Callback
{
public void done()
{
Console.WriteLine("I am done");
}
}

An example run would be as follows:

C#
using System;
using System.Threading;
class Demonstration
{
static void Main()
{
Executor executor = new Executor();
executor.asynchronousExecution(new Callback());
Console.WriteLine("main thread exiting...");
}
}
public interface ICallback
{
void done();
}
public class Callback : ICallback
{
public void done()
{
Console.WriteLine("I am done");
}
}
public class Executor
{
public void asynchronousExecution(ICallback callback)
{
Thread t = new Thread(() =>
{
// Simulate useful work by sleeping for 5 seconds
Thread.Sleep(5000);
callback.done();
});
t.Start();
}
}

Note, the main thread exits before the asynchronous execution is completed. The print-statement from the main thread ...