Home > other >  Class variable not updating in async method
Class variable not updating in async method

Time:08-04

I have a simple async method that is fetching an object from an external API and adding it to a list at the class level. Problem is that the object does not get added to my list when the call is isolated in its own method. However, if I were to put the call in the Form1_Load method, the list will populate fine.

Can someone help explain why this happening?

public partial class Form1: Form
{
    private ApiClient client;
    private List<Object> list;

    public Form1()
    {
        InitializeComponent();

        client = new ApiClient();
        list = new List<Object>();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        GetObject();

        //Adding the call here populates the list successfully
        //list.Add(await client.GetResourceAsync<Object>(1));
    }

    private async void GetObject()
    {
        list.Add(await client.GetResourceAsync<Object>(1));
    }
}

CodePudding user response:

It's asynchronous. It'll update it eventually. If you want to be sure it is updated before you do something, await the call.

private async void Form1_Load(object sender, EventArgs e)
{
    await GetObject();  //Add await here
}

private async Task GetObject() //Change the return type to Task so you can await it
{
    list.Add(await client.GetResourceAsync<Object>(1));
}
  • Related