Make one method wait for the other to finish

1

Good morning everyone, I have the following doubt, when clicking on a button my program does with if you run 2 methods simultaneously, method of sending email, and method of generating the pdf, it happens that the method of sending email always ends before, by example:

anexos.Add(new MemoryStream(PDF));

When it comes to this part of the function to send the email, the variable "PDF" has not yet been created because the function of generating the PDF has not finished yet, I needed a way to make it somehow, the send email function will wait for the PDF to be generated. If anyone can help thank you.

    
asked by anonymous 14.03.2017 / 15:29

2 answers

1

The easiest way here is to use the AutoResetEvent that basically "warns "that something happened.

public void ExecutaTasksAsync()
{
    SomeClass someObj = new SomeClass()
    AutoResetEvent waitHandle = new AutoResetEvent(false); 
    // Cria e adiciona o handler de eventos para o evento demarcando que foi terminado
    EventHandler eventHandler = delegate(object sender, EventArgs e) 
    {
        waitHandle.Set();  // Aviso que o evento terminou
    } 
    someObj.TaskCompleted += eventHandler;

    // Chama o seu outro método async
    someObj.PerformFirstTaskAsync();    
    // Espera até o evento ser sinalizado
    waitHandle.WaitOne();

    // A partir daqui, a task está completa, então só seguir o código normalmente....
}

This is just a sample code, you will have to modify it to fit your code ....

PS: The @jbueno message is correct, it does not make sense for them to be asynchronous if you need to wait for the other.

    
14.03.2017 / 15:39
1

Another option is also to use the Task.ContinueWith . Thus, you ensure that the PDF is always created before sending the email.

ClassePDF pdf = null;

Task.Run(() =>
{
   pdf = CreatePdf();
}).ContinueWith(task =>
{
   //Pode verificar aqui por exceções lançadas na task anterior
   SendEmail(pdf);
});
    
15.03.2017 / 12:54