Make one method wait for the end of the other

Asked

Viewed 1,318 times

1

Good morning, you guys, I am with the following doubt, when clicking a button my program makes to execute 2 methods simultaneously, method of sending email, and method of generating the pdf, it happens that the method of sending email always ends before, for example:

anexos.Add(new MemoryStream(PDF));

When it arrives at this part within the function of sending 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 somehow, the function of sending email wait for the PDF to be generated. If anyone can help, thank you.

  • 1

    It makes sense to run the methods simultaneously if one needs to wait for the other to finish?

  • So it’s just that the structure is a bit messy and that’s the only way I could make rsrs

  • Vc is using async await?

2 answers

1

Another option is to use 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);
});

1


The easiest way here is to use 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 an example code, you will have to modify to suit your code....

PS:: The @jbueno message is correct, it doesn’t make sense that they are asynchronous if you need to wait for each other.

  • Using async await would not avoid all this code?

  • @Thiagolunardi is a solution too, but as I had no information about the code, I opted for a generic solution that works independent of context

Browser other questions tagged

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