Asynchronous Code – Behind the Scenes – 004

During this series of deep dive into the asynchronous calls, we have so far looked into

  • [x] General Structure of generated code.
  • [x] Role of Stub/Worker method.
  • [x] Structure of State Machine and role of Fields.
  • [x] Implementation of the SetStateMachine method.
  • [ ] Implementation of the MoveNext method.

It is now time to look at the most important piece of the puzzle – the MoveNext() method.

Before we begin exploring the MoveNext(), let us remind ourself that the method is called when the async method is first invoked and then, each time it is resumed. The Method would be responsible for the following.

  • Ensure the method starts/resumes execution at the right place when it starts for the first time or resumes after a pause.
  • Preserve the state of State Machine when it needs to pause.
  • Schedule a continuation when the awaited expression hasn’t been completed yet.
  • Retrieve values from the awaiter.
  • Propagate the return values or method completion via the Builder.
  • Propagate the exceptions if any via the Builder.

The last 2 points are curious if you were to consider that the MoveNext method has a void return Type. So how does the MoveNextreturn the result or exceptions ? Of course via the Builder instance. It is the role of the Stub method to return the Task to the Caller method.

Without taking any time longer, let us take a peek at the generated code. We will then proceed to split it into parts and find how it works

The Whole Code

private void MoveNext()
{
    int num = <>1__state;
    try
    {
        TaskAwaiter awaiter;
        if (num != 0)
        {
            if (num == 1)
            {
                awaiter = <>u__1;
                <>u__1 = default(TaskAwaiter);
                num = (<>1__state = -1);
                goto IL_00cc;
            }
            awaiter = Task.Delay(delay).GetAwaiter();
            if (!awaiter.IsCompleted)
            {
                num = (<>1__state = 0);
                <>u__1 = awaiter;
                <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
                return;
            }
        }
        else
        {
            awaiter = <>u__1;
            <>u__1 = default(TaskAwaiter);
            num = (<>1__state = -1);
        }
        awaiter.GetResult();
        Console.WriteLine(delay);
        awaiter = Bar().GetAwaiter();
        if (!awaiter.IsCompleted)
        {
            num = (<>1__state = 1);
            <>u__1 = awaiter;
            <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
            return;
        }
        goto IL_00cc;
        IL_00cc:
        awaiter.GetResult();
    }
    catch (Exception exception)
    {
        <>1__state = -2;
        <>t__builder.SetException(exception);
        return;
    }
    <>1__state = -2;
    <>t__builder.SetResult();
}

That does look a bit scary to begin with. But, have no worries. We will break it down and understand it better.

Exception Handling

Now we already know that the associated Task object returned by the async method would contain any exception if any. It also sets the status to faulted. So how does the State Machine help in doing so ? That’s the first part we will explore. Let us have birds-eye view of the MoveNext() method – for time being, we will ignore all code within the try block.

private void MoveNext()
{
    int num = <>1__state;
    try
    {
        // Ignore this code for the moment
    }
    catch (Exception exception)
    {
        <>1__state = -2;
        <>t__builder.SetException(exception);
        return;
    }
    <>1__state = -2;
    <>t__builder.SetResult();
}

As you can observe the entire MoveNext() method has a big try catch wrapping the code within. The interesting part for the moment would be the catch block. If any exceptions occurs in the try block, the MoveNext() method sets the state to -2 to indicate the method has completed (-2 indicates completion, irrespective of success or failure). It then uses the Builder to set the exception using the Builder.SetException method.

Only special exceptions like the ThreadAbortException or the StackOverflowException can cause the MoveNext() method to end with an exception.

High Level Flow of State Machine

At a higher level, one can observe that the MoveNext() method returns if any of the following are true

  • Each time the state machine needs to be pause (for an await statement to complete).
  • Execution reaches the end of the method
  • Exception is thrown, but not caught in the async method.

A High level flow of the State Machine could be summarized as follows.

  1. The Stub Method (Worker Method) initiates the State Machine using the Builder Object (AsyncTaskMethodBuilder).
  2. Jump to the correct place in State Machine based on the State Field.
  3. Execute the State Machine until the code reaches await statement or end of the method (return statement).
  4. Fetch the awaiter.
    • If the awater is completed, go back to the Step 2.
    • If not, attach a continuation to the awaiter.
    • If this is the first awaiter, return the Task.
  5. The Task returned in Step 5, would be returned the caller via the Builder.

The Try Block

The Try blocks starts with a switch/if condition depending on the number of await statements within the method. If it has 3 or more awaits, usually one could notice a switch case, in all other cases, an if statement is used.

Irrespective of the approach, the condition to check resolves around the State of the State Machine. If the state is negative, it indicates the first call to the MoveNext() method. If the value of State is a positive number, then it indicates the State Machine is resuming from a pause.

public int <>1__state;
public AsyncTaskMethodBuilder <>t__builder;
public int delay;
private TaskAwaiter <>u__1;

private void MoveNext()
{
    int num = <>1__state;
    try
    {
        TaskAwaiter awaiter;
        if (num != 0)
        {
            if (num == 1)
            {
                awaiter = <>u__1;
                <>u__1 = default(TaskAwaiter);
                num = (<>1__state = -1);
                goto IL_00cc;
            }
            awaiter = Task.Delay(delay).GetAwaiter();
            if (!awaiter.IsCompleted)
            {
                num = (<>1__state = 0);
                <>u__1 = awaiter;
                <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
                return;
            }
        }
        else
        {
            awaiter = <>u__1;
            <>u__1 = default(TaskAwaiter);
            num = (<>1__state = -1);
        }
        awaiter.GetResult();
        Console.WriteLine(delay);
        awaiter = Bar().GetAwaiter();
        if (!awaiter.IsCompleted)
        {
            num = (<>1__state = 1);
            <>u__1 = awaiter;
            <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
            return;
        }
        goto IL_00cc;
        IL_00cc:
        awaiter.GetResult();
    }
    catch (Exception exception)
    {
        // Not displayed for clarity
    }
    <>1__state = -2;
    <>t__builder.SetResult();
}

One of the first things you notice in the code above is that State is stored in a local variable. I guess this is done for optimization purposes. We could use a dedicated post later for understanding different optimizations techniques used by compiler here, for now let us stick to the task in hand.

As one can observe, when the Method is invoked for the first time, as the state would be -1, the code would proceed and hit the first await statement.

awaiter = Task.Delay(delay).GetAwaiter();
if (!awaiter.IsCompleted)
{
    num = (<>1__state = 0);
    <>u__1 = awaiter;
    <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
    return;
}

It fetches the Awaiter using the GetAwaiter method. If the awaiter is already completed, it would proceed to the next step in the original method. If not, it would set the State to 0 (indicating the first instance where the MoveNext() method had to await – zero based index), store the awaiter in the field and schedules the state machine to proceed to the next action when the specified awaiter completes using the Builder.AwaitUnsafeOnCompleted method.

On resumption after the pause, it moves to else part (remember, the state is having a value 0 now). It restores the awaiter stored in the field and clears the fields so that GC could take care of it. It also sets the State to -1.

else
{
    awaiter = <>u__1;
    <>u__1 = default(TaskAwaiter);
    num = (<>1__state = -1);
}
awaiter.GetResult();
Console.WriteLine(delay);
awaiter = Bar().GetAwaiter();
if (!awaiter.IsCompleted)
{
    num = (<>1__state = 1);
    <>u__1 = awaiter;
    <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
    return;
}

It then proceeds to fetch the Result using the TaskAwaiter.GetResult() method and then executes the remaining steps untill it hits the next await or the method completes. On completion (either finished or faulted), it sets the State to -2 and sets the Result using the Builder.

<>1__state = -2;
<>t__builder.SetResult();

Over the last few posts, we have traced through the generated source code behind the asynchronous methods. We noticed how the method gets translated to a pair of Stub/Working method and a State Machine. We also explored the State Machine in detail and understood how the MoveNext method method navigates the original method while maitaining the states.

The whole process, starting from the moment your code hits the await expression could be summarized as,

  1. Get the awaiter from the awaitable expression using the GetAwaiter() method.
  2. Check if the awaiter has been comepleted
    • If Yes, Go to Step 8. (Fast Path)
    • If No, remember where you have reached using the State Field. (Slow Path)
  3. Store the awaiter in a field.
  4. Schedule a continuation with the awaiter, such that when the continuation is executed, you are back at the right place.
  5. Return from the MoveNext, either to the original caller if it is the first pause, or to whatever has scheduled the continuation.
  6. When the continuation fires, set the State to -1 to indicate running.
  7. Restore the Awaiter from the field and store it back in the Stack. Remember to reset the field so that GC could take care of it.
  8. Fetch the result using GetResult() method.
  9. Continue with rest of the code.

This, was a simple asynchornous method devoid of any controls methodologies like the loops. In the next part of this series, we will use the knowledge we have gained so far to understand more complex scenarios in depth.

Once again, I would like to thank the wonderful Jon Skeets for his brillant book – C# in Depth. You ought to rename it to “C# Bible” Jon !!

Asynchronous Code – Behind the Scenes – 003

Okay, I wasn’t quite realistic in the earlier post when I mentioned we would look at MoveNext in this one. I missed an important clog of the wheel. The SetStateMachine() method.

IAsyncStateMachine.SetStateMachine

We will only breifly visit the SetStateMachine method here, as the complete picture becomes more clear when we look to details of the MoveNext() method.

So how does the SetStateMachine method looks like in the generated code. Interestingly, it has two different implementation depending on whether you are in Release or Debug mode.

// Release Mode
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine stateMachine)
{
    <>t__builder.SetStateMachine(stateMachine);
}

void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
{
    this.SetStateMachine(stateMachine);
}


// Debug Mode
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine stateMachine)
{
}

void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
{
    this.SetStateMachine(stateMachine);
}

As one can observe, in the Debug Mode, the method is empty. Hence the following explanation is more relavant for the Release mode.

Let’s go back a bit and think about our little Stub method.

private static Task Bar()
{
	<Bar>d__2 stateMachine = new <Bar>d__2();
	stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
	stateMachine.<>1__state = -1;
	stateMachine.<>t__builder.Start(ref stateMachine);
	return stateMachine.<>t__builder.Task;
}

When the State Machine is started by the Stub Method, it is residing on the Stack as a local variable of the Stub Method.

This is where the whole crazy stuff starts. When the State Machine pauses and resumes again, it needs a lot of information. For this to happen, when it pauses, the state machine has to box itself and store in heap, so that when it resumes, it has all the necessary informations. After it is boxed, the state machine is called on the box value using box value as arguement.

Do note that the boxing happens only once. The State machine also ensures that the builder has a reference to the single boxed version of the state machine.

This can be noticed if you dig a deep into the code of AsyncMethodBuilderCore.SetStateMachine

public void SetStateMachine(IAsyncStateMachine stateMachine)
{
	if (stateMachine == null)
	{
		throw new ArgumentNullException("stateMachine");
	}
	if (m_stateMachine != null)
	{
		throw new InvalidOperationException(Environment.GetResourceString("AsyncMethodBuilder_InstanceNotInitialized"));
	}
	m_stateMachine = stateMachine;
}

We will leave the SetStateMachine here because that’s all it does. Its role would be more visible once we examine the MoveNext method in detail.

Asynchronous Code – Behind the Scenes – 002

In the earlier part of this series, we reviewed the generic structure of decompiled async code, especially the stub method. In this part, we would continue our explore of async code and look into the State Machine. We would not delve deep into the most important MoveNext() method yet, we will first familiar with the different parts of the State Machine first.

State Machine

Let us go back to the ILSpy and see how State Machine looks like.

[StructLayout(LayoutKind.Auto)]
[CompilerGenerated]
private struct <Foo>d__1 : IAsyncStateMachine
{
	public int <>1__state;

	public AsyncTaskMethodBuilder <>t__builder;

	public int delay;

	private TaskAwaiter <>u__1;

	private void MoveNext()
	{
		// To be discussed later
	}

	void IAsyncStateMachine.MoveNext()
	{
		//ILSpy generated this explicit interface implementation from .override directive in MoveNext
		this.MoveNext();
	}

	[DebuggerHidden]
	private void SetStateMachine(IAsyncStateMachine stateMachine)
	{
		<>t__builder.SetStateMachine(stateMachine);
	}

	void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
	{
		//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
		this.SetStateMachine(stateMachine);
	}
}

  • IAsyncStateMachine Interface

One of the first things we would notice is the implementation of IAsyncStateMachine interface. The IAsyncStateMachine interface, which is defined under the System.Runtime.CompilerServices namespace, represents the state machine generated for the async method. The interface itself is a simple one, with just two methods in it.

public interface IAsyncStateMachine
{
    /// <summary>Moves the state machine to its next state.</summary>
    void MoveNext();
    /// <summary>Configures the state machine with a heap-allocated replica.</summary>
    /// <param name="stateMachine">The heap-allocated replica.</param>
    void SetStateMachine(IAsyncStateMachine stateMachine);
}

The MoveNext() as explained earlier, represents the heart of asynchronous code. We would, for time being, delay visiting the method for a bit longer. However, the key point to remember at this point of time is that each time the State Machine is starts or resumes (after a pause), the MoveNext() method would be called. The SetStateMachine() method associates the builder with the specific state machine.

The importance of the implementation of the interface and how it binds the state machine with the stub method could be understood by looking at the signature of the AsyncTaskMethodBuilder.Start(). The method accepts a single generic parameter, which has a constraint of having implemented the IAsyncStateMachine.

public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
	if (stateMachine == null)
	{
		throw new ArgumentNullException("stateMachine");
	}
	ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher);
	RuntimeHelpers.PrepareConstrainedRegions();
	try
	{
		ExecutionContext.EstablishCopyOnWriteScope(ref ecsw);
		stateMachine.MoveNext();
	}
	finally
	{
		ecsw.Undo();
	}
}

We would not go too deep into AsyncTaskMethodBuilder.Start(), but key take away would be

  • The constraint applied to parameter where TStateMachine : IAsyncStateMachine
  • The method is responsible for calling IAsyncStateMachine.MoveNext()

There is another interesting fact to this look at this point. The generated State Machine has a small but significant difference depending on whether your are looking at debug/release mode code. When in release mode, the compiler optimizes the code and creates a stuct based State Machine, while in debug mode, it creates a class. This is supposed to an optimization done to so that the compiler would skip allocating memory when the awaitable has already been completed awaited. The following code displays the State Machine when decompiled in debug mode.

[CompilerGenerated]
private sealed class <Foo>d__1 : IAsyncStateMachine
{
	public int <>1__state;

	public AsyncTaskMethodBuilder <>t__builder;

	public int delay;

	private TaskAwaiter <>u__1;

	private void MoveNext()
	{
		// To be discussed later
	}

	void IAsyncStateMachine.MoveNext()
	{
		//ILSpy generated this explicit interface implementation from .override directive in MoveNext
		this.MoveNext();
	}

	[DebuggerHidden]
	private void SetStateMachine(IAsyncStateMachine stateMachine)
	{
	}

	void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
	{
		//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
		this.SetStateMachine(stateMachine);
	}
}


  • Fields

public int <>1__state;
public AsyncTaskMethodBuilder <>t__builder;
public int delay;
private TaskAwaiter <>u__1;

The next thing one would notice with the generated code is the presence of certains fields in the state machine. The fields could be broadly categorized into

  • Current State : As discussed in earlier post, this could have any of the following values
-1 : Not Started
-2 : Completed
Any other Value : Paused

  • Method Builder : Communicates with the async infrastructure and returns the task
  • TaskAwaiter
  • Parameters and local variables
  • Temporary Stack Variables

TaskAwaiter and parameters are used to remember the values when the State Machine resumes after a Pause. If the state machine requires a variable which it doesn’t need to remember after resuming, then it remains as private variable.

Temporary stack variables are used as a part of larger expression, when the compiler needs to remember intermediate results. For example,

int result = x + y + await task;

The most important point to remember about the Fields and Variables is that the compiler ensures it uses minimum fields/variables as possible by reusing them.

If your code have multiple await that was supposed to return

  • Task<int>
  • Task<string>
  • Task

Then the compiler would most likely create just 3 awaiters, one each for the different types involved.

That is it about the general structure of the State Machine. We would now proceed to the most important part, which is of course the MoveNext() method. We will do it in the next post.

Asynchronous Code – Behind the Scenes – 001

If you were to ask me what was the biggest milestone in .Net development, then my choice would definetly be .Net 5.0 – especially the introduction of the async/await. The more you learn about the underlying working, you cannot but stop and admire the efforts done by the lang uage developers to make our life easier.

In this mini series on asynchronous programming in .Net, we will delve deeper into the fascinating world of async await and learn more about what happens behind the scenes. I thought i would structure it as a mini-series rather than a single monolythic post as this is a vast topic (at least for an average developer like me).

Setting the Stage

Let us begin by writing a simple async method, which we would then decompile using ILSpy to know what happens beneath. We will keep the base code as simple as possible.

class Program
{
    static void Main(string[] args)
    {
        Foo(10);
    }

    static async Task Foo(int delay)
    {
        await Task.Delay(delay);
        Console.WriteLine(delay);
        await Bar();
    }

    static async Task Bar()
    {
        await Task.Delay(100);
    }
}

For the demonstration purpose, we will use ILSpy for decompiling our code, but please feel free to choose any decompiler you are comfortable with. In case you are using ILSpy, please ensure you have the following settings unchecked.

View->Options->Decompiler->C# 5.0-> Decompile async methods

This would ensure we could view the decompiled async code and the associated state machine. Okay, now let us see what ILSpy has to offer us after decompiling our code. We will read the code in parts, so that it is easier for us to understand the whole structure.

  1. Stub Method
  2. State Machine structure
  3. MoveNext Method method

Stub Method

As you would be already aware, the async methods are implemented with the help of State Machines internally.

Stubs are methods which has the same signature as your original async method and is responsible for creating the state machine. Let us check the decompiled stub method.

[AsyncStateMachine(typeof(<Foo>d__1))]
[DebuggerStepThrough]
private static Task Foo(int delay)
{
	<Foo>d__1 stateMachine = new <Foo>d__1();
	stateMachine.delay = delay;
	stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
	stateMachine.<>1__state = -1;
	stateMachine.<>t__builder.Start(ref stateMachine);
	return stateMachine.<>t__builder.Task;
}

[AsyncStateMachine(typeof(<Bar>d__2))]
[DebuggerStepThrough]
private static Task Bar()
{
	<Bar>d__2 stateMachine = new <Bar>d__2();
	stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
	stateMachine.<>1__state = -1;
	stateMachine.<>t__builder.Start(ref stateMachine);
	return stateMachine.<>t__builder.Task;
}

Let us skip the attributes for a moment (we will come back to very shortly), and first concentrate on signature of both Stub methods. As mentioned earlier, both shares the same signature with their original async methods.

The Stub Method is responsible for creating/initializing the State Machine and Starting it. The state machines are initialized with following

  • Parameters as Fields

Any parameter in the original async method are added as Fields in the State Machine. For example, if you inspect the following code from Foo Stub Method.

stateMachine.delay = delay;

The Foo method, if you remember, accepted a single parameter of Type int and was called delay. This parameter would be now added a field in the State Machine.

  • Type of Builder

The type of Builder varies depending on the return type of the Method in question.

Return TypeBuilder
TaskAsyncTaskMethodBuilder
Task<TResult>AsyncTaskMethodBuilder<T>
voidAsyncVoidMethodBuilder
Custom Task TypeBuilder specified by AsyncTaskMethodBuilderAttribute

In the above scenario, both methods returns Task. For the same reason, the both uses an AsyncTaskMethodBuilder. Please note that the Custom Task Type was introduced only with C# 7. Prior to C# 7, only the first 3 builders were applicable.

The attribute AsyncStateMachine points to the method’s particular state machine and aids in tooling.

  • State of the State Machine

A async method could be in either the following states – Not Started – Executing – Paused – Completed (Successfully or Faulted)

Out of these, the most important state for the State Machine is the Paused State. While in the Executing State, the async method is pretty much like synchronous code as it passes through each instruction. The CPU would keep track of the currently executing step via Instruction Pointer.

However, the state machine comes into picture immediately as the method pauses when it reaches an await (incomplete) expression. Please note that this is applicable only for async expression that has not been completed. In case the awaited expression is completed, the code works similiar to synchronous code and the state machine would not be brought into picture.

Each time the state has to be paused, the state is recorded so that once the operation awaited is completed, the method could be continued.

As one can expected, the Stub method would like to set the initial state of the state machine to Not Started.

The State Property of the state machine handles the current state with following value codes

ValueDescription
-1Not Started
-2Completed (Successfully/Faulted)
Any other valuePaused at an await Expression

As one can observe, these are the values which the Stub method initializes the State Machine with.

<Foo>d__1 stateMachine = new <Foo>d__1();
stateMachine.delay = delay;
stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
stateMachine.<>1__state = -1;
stateMachine.<>t__builder.Start(ref stateMachine);

Additional, it also starts the State Machine using the Builder.Start method, passing a reference to the State Machine created. The important point to note here is that the stateMachine is passed as reference to the method. This is because both StateMachine and AsyncTaskBuilder are mutable value types, and passing the instance by reference ensures no local copy are created. One can notice a lot of optimization done by the compiler.

The final step of the Stub method is of course, to return the Task object. The Task object is created by the Builder, who also ensures the Task’s state is changed accordingly as the method execution progresses.

return stateMachine.<>t__builder.Task;

When the Builder.Start method is invoked, it begins executing the MoveNext method (we will discuss it later) untill the method reaches an incomplete await expression. At this point, the MoveNext would return the Task, following up which, the Start method also returns. The task is then returned to the Caller method.

That’s it for the Stub Method, in the next section, we will look into the State Machine structure.

Awaitable Pattern

How do you determine what types could be awaited ? That is one question that often comes to mind and the most common answer would be

  • Task
  • Task<TResult>
  • void – Though it should be strictly avoided

However, are we truely restricted to them ? What are the other Types that could be awaited ? The anwer lies in the awaitable pattern.

Awaitable Pattern

The awaitable pattern requires to have a parameterless instance or static non-void method GetAwaiter that returns an Awaitable Type.

public T GetAwaiter()

Where T, the awaiter Type implements
* INotifyCompletion or ICriticallyNotifyCompletion
* Has a boolean instance property IsCompleted
* Non-generic parameterless instance method GetResult

Approach 01 – Use TaskAwaiter

Let’s begin by an example that reusing Task or Task<TResult> awaiter instead of creating our own awaiter. For demonstration purpose, we assume a requirement where in we should be able to use the Process Class to execute given command asynchronously and return the result. Ideally, we should be able to do the following.

var result = await "dir"

The above command should be able to execute “dir” command using Process and return the result. We will begin by writing the GetAwaiter extension method for string.

public static class CommandExtension
{
public static TaskAwaiter GetAwaiter(this string command)
{
var tcs = new TaskCompletionSource();
var process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = $"/C {command}";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.EnableRaisingEvents = true;
process.Exited += (s, e) => tcs.TrySetResult(process.StandardOutput.ReadToEnd());
process.Start();
return tcs.Task.GetAwaiter();
}
}

The above code reuses the Awaiter for Task<TResult>. The method initiates the Process and use TaskCompletionSource to set the result in the Exited event of Process. If you examine the source code of TaskAwaiter , you can observe that it implements the ICriticallyNotifyCompletion interface and has the IsCompleted Property as well as GetResult method.

Let us now write some demonstrative code.

private async void btnDemoUsingTaskAwaiter_Click(object sender, EventArgs e)
{
AppendToLog($"Started Method {nameof(btnDemoUsingTaskAwaiter_Click)}");
await InvokeAsyncCall();
AppendToLog($"Continuing Method {nameof(btnDemoUsingTaskAwaiter_Click)}");
}
private async Task InvokeAsyncCall()
{
AppendToLog($"Starting Method {nameof(InvokeAsyncCall)}");
var result = await "dir";
AppendToLog($"Recieved Result, Continuing Method {nameof(InvokeAsyncCall)}");
AppendToLog(result);
AppendToLog($"Ending Method {nameof(InvokeAsyncCall)}");
}
public void AppendToLog(string message)
{
logText.Text += $"{Environment.NewLine}{message}";
}

Approach 02 – Implement Custom Awaiter

Let us now assume another situation where-in, the method is invoked in a non-UI thread, and the continuation requires you to update Controls in UI (in other words, needs UI Thread). For purpose of learning, let us find a solution for the problem by implementing a Custom Awaiter.

We will begin by defining our Custom Awaiter that satisfies the laws defined in the Awaitable Pattern section above.

public static class CommandExtension
{
public static UIThreadAwaiter GetAwaiter(this string command)
{
var tcs = new TaskCompletionSource();
Task.Run(() =>
{
var process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = $"/C {command}";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.EnableRaisingEvents = true;
process.Exited += (s, e) => tcs.TrySetResult(process.StandardOutput.ReadToEnd());

process.Start();
});

return new UIThreadAwaiter(tcs.Task.GetAwaiter().GetResult());
}
}
public class UIThreadAwaiter : INotifyCompletion
{
bool isCompleted = false;
string resultFromProcess;

public UIThreadAwaiter(string result)
{
resultFromProcess = result;
}
public bool IsCompleted => isCompleted;
public void OnCompleted(Action continuation)
{
if (Application.OpenForms[0].InvokeRequired)
Application.OpenForms[0].BeginInvoke((Delegate)continuation);

}

public string GetResult()
{
return resultFromProcess;
}
}

The UIThreadAwaiter implements the INotifyCompletion interface. As one could asssume from the code above, the ability to use UI Thread for continuation tasks are executed with the help of BeginInvoke.

Let us now write some demo code to demonstrate the custom awaiter.

private void btnExecuteOnDifferentThread_Click(object sender, EventArgs e)
{
AppendToLog($"Started Method {nameof(btnExecuteOnDifferentThread_Click)}");
Task.Run(() => InvokeAsyncCall()).ConfigureAwait(false);
AppendToLog($"Continuing Method {nameof(btnExecuteOnDifferentThread_Click)}");
}

private async Task InvokeAsyncCall()
{
var result = await "dir";
AppendToLog($"Recieved Result, Continuing Method {nameof(InvokeAsyncCall)}");
AppendToLog(result);
AppendToLog($"Ending Method {nameof(InvokeAsyncCall)}");
}
public void AppendToLog(string message)
{
try
{
txtLog.Text += $"{Environment.NewLine}{message}";
}
catch (Exception ex)
{
var errorMessage = $"Exception:{ex.Message}{Environment.NewLine}{Environment.NewLine}Message:{message}";
MessageBox.Show(errorMessage, "Error");
}
}

private async void btnExecuteOnSameThread_Click(object sender, EventArgs e)
{
AppendToLog($"Started Method {nameof(btnExecuteOnDifferentThread_Click)}");
await InvokeAsyncCall();
AppendToLog($"Continuing Method {nameof(btnExecuteOnDifferentThread_Click)}");
}

As demonstrated in examples above, the await keyword is not restricted to few types. Instead, we could create our Custom Awaiter which statisfies the Awaitable Pattern.

Complete code for this post is available on my Github