Sobes.tech
Junior — Middle

How do approaches to implementing asynchronous operations differ in C# and JavaScript?

sobes.tech AI

Answer from AI

In C# and JavaScript, asynchronous operations are implemented differently, although the goal is the same — to avoid blocking the main thread.

C#:

  • Uses the keywords async and await for working with tasks (Task).
  • Asynchrony is based on a task model and a thread scheduler.
  • Allows writing asynchronous code that resembles synchronous code, improving readability.

Example:

public async Task<string> GetDataAsync()
{
    var result = await httpClient.GetStringAsync("https://example.com");
    return result;
}

JavaScript:

  • Asynchrony is based on an event loop and promises.
  • Uses Promise, async/await for working with asynchronous code.
  • Asynchronous operations do not create new threads but work in a single thread with non-blocking I/O.

Example:

async function getData() {
  const response = await fetch('https://example.com');
  const data = await response.json();
  return data;
}

The main difference: C# uses multithreading and a task scheduler, while JavaScript is single-threaded with an event loop and non-blocking I/O.