A Beginners Guide to GraphQL Dotnet CancellationToken
Tags: graphql, csharp, beginners, dotnet
Published: 2022-10-14 15:26:16

In the early 2000s, the REST API gained much fame in the technology sector due to its multipurpose functionality and responsiveness. However, despite the increased usage, the developer community encountered an issue of over-fetching data points. The data holds core importance in any web or mobile application. Apart from it, the excessive retrieval of data can slow the process and may further lead to an unresponsive server as well.

In order to tackle the growing concern, the Graph Query Language was developed by Facebook to make its app more responsive and reliable. GraphQL is an API standard, particularly an alternative to REST APIs. Unlike the traditional REST API, this solution grants the control to the client to directly request the specified data rather than irrelevant data.

The goal of GraphQL is to make APIs quick, adaptable, and developer-friendly. In contrast to REST, GraphQL APIs allow data to be retrieved and delivered from different sources while accepting all incoming requests at a single endpoint.

**- GraphQL Dotnet**
[GraphQL](https://clearinsights.io/blog/a-beginners-guide-to-graphql-dotnet-cancellationtoken/) is not only bounded to specific backend languages but can also be used to develop projects in Dotnet. There are numerous platforms and languages in the GraphQL ecosystem. Despite the fact that .NET was slow to implement support, several widely used client and server solutions are available now.

A basic example of **GraphQL.NET using the System.Text.Json serialization engine.**
```
using System;
using System.Threading.Tasks;
using GraphQL;
using GraphQL.Types;
using GraphQL.SystemTextJson;
public class Program
{
    public static async Task Main(string[] args)
    {
        var schema = Schema.For(@"
            type Query {
                hello: String
            }
        ");
        var json = await schema.ExecuteAsync(_ =>
        {
            _.Query = "{ hello }";
            _.Root = new { Hello = "Hello World!" };
        });
        Console.WriteLine(json);
    }
}
```
**Output:**

```
{
   "data":{
      "hello":"Hello World!"
   }
}
```

**- Defining Schema in GraphQL**
As GraphQL is a structured Graph Query Language, it must have its schema defined. In order to design its schema, two approaches can be utilized:

**- Schema First Approach (Using GraphQL)**
This approach is believed to be the simplest one to get started with, and it has limitations for advanced implementations and scenarios. This methodology’s practical procedure lies upon the GraphQL schema language and syntaxes, resulting in a minimal syntax approach. 

**- GraphType (Code First Approach)**
Although the GraphType technique can be more expansive and has a higher Line of Code (LOC). Furthermore, GraphType implementation allows the developers access to every property that GraphType and Schema provide. To use this methodology, Object Oriented Programming (OOP) paradigm is opted for, and Inheritance is used to leverage this functionality.

**- CancellationToken in Dotnet**
In a web-based application, the request from the client and the reposne from the server sides are standard ways of communication between stakeholders. However, such scenarios exist too, where a client-server interaction is interrupted, and the client-side becomes unresponsive.

Once a user gets disconnected due to a network interruption, navigating between multiple browser tabs, or closing the browser, the request becomes an orphan. Whereas an orphan request cannot deliver a response to the client, it will still communicate with the server, resulting in a recursive process and further leading to excessive memory usage by the particular process.

To prevent a process from making irregular and consistent calls to the server side, the CancellationToken is used. It terminates the request execution at the server immediately.

Canceling tasks in Dotnet/C# is not tricky. However, there are several ways to do so. The three commonly used methods include:

1. **Polling**
2. **Registering a Callback**
3. **Wait Handle**

Additionally, multiple tokens can be canceled at once as the polling strategy is designed for situations where there are lengthy computations that loop or recurse.

**The typical procedure followed when canceling a task using CancellationToken:**

1. Instantiate a **CancellationTokenSource** object. This object manages and sends the cancellation notification to the individual cancellation tokens.
2. Passing the token returned by the CancellationTokenSource. Token property to each task or thread that listens for cancellation.
3. Providing a mechanism for the thread to respond to cancellation. The token cannot be used to initiate a cancellation
4. Calling the CancellationTokenSource.
5. When the owning object calls CancellationTokenSource.Cancel, the IsCancellationRequested property on every copy of the cancellation token is set.
6. Canceling method to provide notification of cancellation.

**- GraphQL Dotnet CancellationToken**
When GraphQL.NET is used, the query fetches results, and the conditions exist where the proper process synchronization needs to be done by canceling excessive tasks at once. The CancellationToken may be used to prevent an application failure or unresponsive behavior as cooperative cancellation between threads or Task objects is made possible through a CancellationToken.

**- ClearInsights Application Logging & Monitoring**
To prevent your application from failing at runtime or crashing, use ClearInsights application performance and [uptime monitoring](https://clearinsights.io/monitoring/) for your deployed systems. Furthermore, with our extensive integrated monitoring for applications & services in any environment, you can keep developers, product teams, and stakeholders informed.