iMasters.com - Knowledge for Developers.
Follow Us
Home Backend How to implement a function using context
Backend

How to implement a function using context

In this post, we will implement a function that uses context. In the calling example, I will use the WithTimeout context. In this way, we will be able to make the function be canceled automatically, in case its execution time exceeds the time stipulated in the context.

Let’s start by creating a function named doSomeHeavyWork.

To simulate lengthy processing, let’s add a goroutine with a 2-second sleep. This goroutine will receive a channel of type bool. It will signal that the goroutine is finished.

In the struct context.Context, we have a method called Done(). This method returns a channel. When the context is finished, that channel will be closed, and this method returns a channel. This will occur when:

-> WithCancel – when the cancel function is executed;

-> WithDeadline – when the deadline expires;

-> WithTimeout – when timeout is reached.

As we have a control channel for sleep and another for context, we need to add a select to capture the activated channel.

To test our function, let’s create a context with a timeout of 1 second.

When running the program with a gorun main.go, we will have the following result:

Changing the time of our timeout to 3 seconds and running the program again, the result will be, the message work completed!

If you want to know a little more about the types of content available and when they are normally used, I recommend reading our post “Where and which context to use”.

Hope this helps, and until next time!

*The content of this article is the author’s responsibility and does not necessarily reflect the opinion of iMasters.

Written by
Tiago Temporin

SRE at Único, creator of Material Community Components & GoSOAP, maintainer of NGX-Translates, and contributor to prEST.

Leave a comment

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Related Articles

Backend

How to Create a Skill for Amazon’s Virtual Assistant Alexa

If you didn’t know, it is not necessary for an Amazon Echo...

Backend

The APIs role in a 5G world

5G is about to revolutionize how we connect and use technology daily....

Backend

EF Core using AsNoTracking with Identity Resolution

Today we will see the consequences of using AsNoTracking with the Identity...

Backend

Understand key features added in ASP.NET Core 7.0

Version 7.0 of the .NET platform brought many new features in this...