What is TaskCompletionSource class in C#

M.F.M Fazrin
2 min readDec 12, 2022

--

TaskCompletionSource is a class in C# that represents a task that can be passed around and completed at a later time. It lets you set up a task and control how it gets done, instead of having it get done automatically when something else finishes. This can be useful in situations where you want to create a task that depends on some external event or piece of information that isn't yet available.

Here is an example of how you might use TaskCompletionSource to create a task that is completed when a user clicks a button:

// Create a new TaskCompletionSource object
var tcs = new TaskCompletionSource<bool>();

// Set up an event handler for the button's Click event
button.Click += (sender, args) =>
{
// When the button is clicked, set the result of the task to true
tcs.SetResult(true);
};

// Get the task that represents the completion of the button click
var task = tcs.Task;

// Do some other work, and then wait for the task to be completed
await task;

// At this point, we know that the button has been clicked

In this example, the task is created when theTaskCompletionSource object is created, but it isn't completed until the button is clicked. This allows us to use the task in other parts of our code and wait for it to be completed without having to worry about how or when the button is clicked.

--

--

M.F.M Fazrin
M.F.M Fazrin

Written by M.F.M Fazrin

Senior Software Development Specialist @ Primary Health Care Corporation (Qatar)

No responses yet