Running a Method in the background Asp.Net/C# (Async or Thread)

Asked

Viewed 788 times

0

What I needed to do was this

  1. Calling a Post Method Called Cadastrar
  2. Before this method finish I would call a new method called PessoaNotificacao

However the method Registration would not wait for the PessoaNotificação finalize for it to continue, I would like that the PessoaNotificação execute in the background.

I read a little about the methods Asyn and Await , but I could not understand very well, I would like a brief explanation or some content in which I can take a look to better understand this concept.

  • Related: http://answall.com/questions/7760/operacoes-async-em-asp-net?rq=1

  • There’s that links for questions on the subject at http://answall.com/a/175305/101. It is probably a duplicate of one of them. Or the question is unclear.

1 answer

1


I see that all you need to do is fire an event and forget, so the async/await is not the best option, after all the await will wait for the return.

You can achieve the expected result as follows.:

public class Program
{
    public void Main()
    {       
        // Realiza algum processo;
        this.Cadastrar();
        // Realiza algum processo;
    }

    public void Cadastrar()
    {
        // Realiza algum processo;
        Task.Run(() => this.PessoaNotificacao(pessoa.Nome));
        // Realiza algum processo;
    }

    public void PessoaNotificacao(string nome)
    {
        // realiza algum processo longo.
    }
}

In the example above the Cadastrar will continue execution in parallel to PessoaNotificacao.

In any case there is no guarantee that the PessoaNotificacao will successfully finish the execution, so the best thing to do is to use the HangFire to manage the execution of the same.:

public class Program
{
    public void Main()
    {       
        // Realiza algum processo;
        this.Cadastrar();
        // Realiza algum processo;
    }

    public void Cadastrar()
    {
        // Realiza algum processo;
        BackgroundJob.Enqueue(() => Program.PessoaNotificacao(pessoa.Nome));
        // Realiza algum processo;
    }

    [DisplayName("Notificação enviada para {0}")]
    public static void PessoaNotificacao(string nome)
    {
        // realiza algum processo longo.
    }
}
  • Oh cool, just a doubt, for example: I call a method to register, will enter it and inside it I have this Task.run(this.Personal notification). Assuming that the notification is delayed, the registration will finish returning the web page and the notification would be running in the background ?

  • @Williamcézar made an edition.

  • Sorry for the delay of the return, I will test today, but I think that’s right, soon I return to mark as sure the answer

  • Perfect your answer, this worked as it should, thank you very much Tobias Mesquita.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.