Running a Background Method Asp.Net/C# (Async or Thread)

0

What I needed to do was the following

  • Call a Post method that is called Cadastrar
  • Before this method finish I would call a new method called PessoaNotificacao
  • However, the Register method would not wait for PessoaNotificação to finish so it could continue, I would like PessoaNotificação to run in the background.

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

        
    asked by anonymous 06.01.2017 / 17:35

    1 answer

    1

    I see that all you need is to trigger an event and forget, so async/await is not the best option, after all 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 above example, Cadastrar will continue execution parallel to PessoaNotificacao .

    In any case, there is no guarantee that PessoaNotificacao will finish execution successfully, so the best thing to do is to use 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.
        }
    }
    
        
    06.01.2017 / 19:18