0

My OnAppearing message is async and from that I call another async method which has some code that modifies the UI. I then do some work and finally modify the UI again.

Here's the code. However I am getting a warning message that confuses me. I added the warning code below.

protected async override void OnAppearing()
{
    base.OnAppearing();
    // actions
    CreateListSectionAsync();
}

public async void CreateListSectionAsync()
{
    // modify UI
    // do some work that takes time
    await Task.Run(() =>
    {
       Device.BeginInvokeOnMainThread(() =>
       {
          // modify UI           
       });
    });
}

ListPage.xaml.cs(39,39): Warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. (CS1998)

Why am I getting this warning and how can I fix it?

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • Put `await` in front of it. – user247702 Mar 21 '19 at 17:38
  • 2
    Well it's correct - your `OnAppearing` method *isn't* awaiting anything. What effect do you expect making it an `async` method to have? As an aside, I'd *strongly* recommend making all your async methods return `Task` instead of `void` unless you absolutely have to. – Jon Skeet Mar 21 '19 at 17:38
  • I tried putting await in front and it says 'cannot await void' – Alan2 Mar 21 '19 at 17:41
  • 2
    As Jon said, have them return `Task` instead of `void`. See [this question](https://stackoverflow.com/questions/13636648/wait-for-a-void-async-method). You should probably stop programming for 15 minutes and take the time to read [Asynchronous Programming with async and await](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/). – user247702 Mar 21 '19 at 17:46
  • 1
    You should not be using `BeginInvokeOnMainThread` here (in fact it's almost never appropriate to use methods like that). Just modify the UI outside of `Task.Run`. – Servy Mar 21 '19 at 17:48
  • 2
    Why do you have an `async void` method in the first place? That's a very bad programming practice; there are situations where it is unavoidable, but this does not appear to be one of them. Can you explain what you're trying to accomplish by making an `async void`? Pretty much all of this code looks wrong, so take a step back and say more clearly what you're trying to do. – Eric Lippert Mar 21 '19 at 19:14

1 Answers1

0
await CreateListSectionAsync();

Change the signature of the fuction to return a Task not void

 public async Task CreateListSectionAsync()
MrVoid
  • 709
  • 5
  • 19