Home > Software design >  async function running in sequence WPF
async function running in sequence WPF

Time:10-05

so I am making a small WPF app.

I am new to C# and Multithreading, I want to run certain methods in sequence but because one of the methods is Async it does not run in sequence.

   private async void LoadButton_Click(object sender, RoutedEventArgs e)
{

    if (!OpenFile()) return; // opens a file dialog and ensure format is correct
  
    await Task.Run(() =>
    {
        // some heavy task which I run here so that I dont freeze the UI
    });

   

}
private void TheFunctionIwantToRunInSeqeuence(object sender, RoutedEventArgs e)
{
    LoadButton_Click(sender, e); 

    SaveCareerInfoButton_Click(sender, e); // I want this line to wait for load to finish

    LoadButton_Click(sender, e); 

    ImportCareerInfoButton_Click(sender, e); // I want this line to wait for the second load to finish
   

}

CodePudding user response:

You can use await to wait an async function to finish and make function TheFunctionIwantToRunInSeqeuence to async Task return type:

private async Task TheFunctionIwantToRunInSeqeuence(object sender, RoutedEventArgs e)
{
    await LoadButton_Click(sender, e); 

    SaveCareerInfoButton_Click(sender, e); // I want this line to wait for load to finish

    await LoadButton_Click(sender, e); 

    ImportCareerInfoButton_Click(sender, e); // I want this line to wait for the second load to finish
   
}

CodePudding user response:

Await these calls as well, refactor your code a bit.. extract handler's content to a separate method and don't pass senders and args between handlers

private Task Load()
{
    if (!OpenFile()) return;

    return Task.Run(() =>
    {
        // some heavy task which I run here so that I dont freeze the UI
    });
}

private async void LoadButton_Click(object sender, RoutedEventArgs e)
{
    await Load();
}

private async void TheFunctionIwantToRunInSeqeuence(object sender, RoutedEventArgs e)
{
    await Load();

    // refactor your code to not pass sender, e.. SaveCareer();
    SaveCareerInfoButton_Click(sender, e);

    await Load();

    // refactor your code to not pass sender, e.. ImportCareer();
    ImportCareerInfoButton_Click(sender, e);
}
  • Related