locked
How do I do processing while a new screen is loading? RRS feed

  • Question

  • User396757 posted

    I have an app that loads a second screen that is pretty much just a Label and a Button (to return to the first screen). When the screen is called, I want it to load the screen (initially it has a "Working..." message), then do some lengthy calculation, then show the result. Putting everything in OnAppearing() doesn't work, as the screen doesn't appear until the calculation is done. I tried this:

    ``` protected override void OnAppearing() { base.OnAppearing();

    Task DoCalculation = new Task(() => { CalculateResult(); });
    DoCalculation.Start();
    

    } ``` with CalculateResult() putting a value into the screen's Label's Text property, but the Label shows up as blank - and the second time I call the screen, the Button does not appear either.

    How do I get the second screen's OnAppearing to load the screen, then complete a calcualtion and modify the display?

    Thursday, September 10, 2020 3:09 PM

Answers

  • User369978 posted

    Try to await the task in OnAppearing method of second page .

    For example

     protected async override void OnAppearing()
        {
            base.OnAppearing();
    
            await DoCalculation();
        }
    
    
        async Task DoCalculation()
        {
            await Task.Delay(3000);
    
            label.Text = "100";
        }
    

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Friday, September 11, 2020 6:32 AM

All replies

  • User369978 posted

    Try to await the task in OnAppearing method of second page .

    For example

     protected async override void OnAppearing()
        {
            base.OnAppearing();
    
            await DoCalculation();
        }
    
    
        async Task DoCalculation()
        {
            await Task.Delay(3000);
    
            label.Text = "100";
        }
    

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Friday, September 11, 2020 6:32 AM
  • User396757 posted

    Thanks - that works...well, sort of. I can't get C# to recognize "async Task MyFunction()" as a valid function declaration (it throws "not all tasks return a value"), so I ended up using: await Task.Run(() => CalculateResult()); instead of: await CalculateResult();

    Friday, September 11, 2020 3:57 PM