Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
How to control C# Task (async/await in same way as javascript Promise)?

I'm js developer and jumped to C#. I'm learning async/await/Task in C# and can't understand how to control C# Task.

In javascript I can save Promise resolve handler to call it later (and resolve promise), for example, to organize communication between some "badly connected" app parts (request doesn't returns result, but result is sent separately and fires some "replyEvent"), and do something like this:

// javascript
const handlers = {}

// event firing on reply
const replyEventListener = (requestId, result) => {
  if (handlers[requestId]) {
    handlers[requestId](result)
    delete handlers[requestId]
  }
}

const requestFunction = (id, params) => new Promise(resolve => {
  // handler is saved to use later from "outside"
  handlers[id] = resolve;
  // do required request
  makeRequest(params)
})

// .. somewhere in code request becomes simple awaitable
const resultOfRequest = await requestFunction(someUniqueId)

How can I do same with C# Task?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I think the philosophy behind Promise (in JS) and Task (in C#) is different. We don't implement them exactly the same way.

Read the documentation on the MSDN :

  • Task Class - Remarks

  • Task<TResult> Class

You must empty your cup to be able to fill it again.

about 4 years ago · Juan Pablo Isaza Relatório

0

A good article in MSDN is the following which shows examples of how Tasks can be used like Promises in the sense that you can start them and then await them later.

Asynchronous programming with async and await

If you want to await a Task in C# like you would a Promise in JS, you would do the following:

  1. Create a method or function that returns a Task. Usually this will be a Task of some class object. In the article above, it references creating breakfast as an analogy, so you can define FryEggsAsync as a method that takes in an int number of how many eggs to fry and returns a Task<Egg>. The C# convention is to end any function or method name with Async to indicate that a Task is being returned.
  2. Create your Task, which is similar to a Promise in JS, so you could do var eggsTask = FryEggsAsync(2), which would store a Task<Egg> in eggsTask, that you can then await or pass to other functions as needed.
  3. To await your Task to resolve it and get the result, you would simply do await eggsTask.

You can also use Task.WaitAll to await multiple Tasks at once, similar to Promise.all in JS, by passing in an array of Tasks as an argument to that method call. See the Task.WaitAll documentation for some examples of this. The difference here though is that the results are stored separately in each task passed to Task.WaitAll, instead of aggregated together into a results array like in JS with Promise.all, but if you need to await multiple Tasks then this will be an easier way to do so.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda