Skip to content

Repository files navigation

ContextFreeTask

Usage

NuGet package: https://www.nuget.org/packages/ContextFreeTasks/

Use ContextFreeTask struct instead of Task class (System.Threading.Tasks namespace) for return types of async methods.

privateasyncContextFreeTaskFAsync(){ ...}privateasyncContextFreeTask<T>FAsync<T>(){ ...}

These ignore the current synchronization context in the methods. You do not have to write ConfigureAwait(false) anymore.

Task-like

In C# 7, async methods may return other types in addition to Task, Task<T> and void. The returned type must satisfy a certain pattern. These types are called "Task-like".

The ContextFreeTask struct in this library satisfies the "Task-like" pattern and the "awaitable" pattern.

What ContextFreeTask does

The methods which return ContextFreeTask do not capture the synchronization context.

For example, you can use this as following:

// All awaits in this method don't capture SynchronizationContextprivateasyncContextFreeTaskFAsync(){// Whatever current context isawaitTask.Delay(100);// no context hereawaitTask.Delay(100);// no context here}

This code behaves almost the same as the following:

privateasyncTaskFAsync(){awaitTask.Delay(100).ConfigureAwait(false);awaitTask.Delay(100).ConfigureAwait(false);}

Implementation

The ContextFreeTask struct is a thin wrapper of Task class.

publicstructContextFreeTask{publicTaskTask{get;}}

And the ContextFreeTask<T> is that of Task<T>.

publicstructContextFreeTask<T>{publicTask<T>Task{get;}}

Those AsyncMethodBuilders always clear current synchronization context.

publicstructAsyncContextFreeTaskMethodBuilder{privateAsyncTaskMethodBuilder_methodBuilder;publicvoidAwaitOnCompleted<TAwaiter,TStateMachine>(refTAwaiterawaiter,refTStateMachinestateMachine)whereTAwaiter:INotifyCompletionwhereTStateMachine:IAsyncStateMachine{varprevContext=SynchronizationContext.Current;try{SynchronizationContext.SetSynchronizationContext(null);_methodBuilder.AwaitOnCompleted(refawaiter,refstateMachine);}finally{SynchronizationContext.SetSynchronizationContext(prevContext);}}}

About

Task-like structs which capture no synchronization context on the await operations.

Resources

Stars

40 stars

Watchers

6 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages