3

I have a Winform C# application, that has a DataGridView. I intend to load data from Azure table storage into it meanwhile the form is initializing. I'm afraid if I load so much data from Azure table storage, my app will be crashed. Can I use Async load data from Azure table storage in form constructor?

Young
  • 97
  • 7

1 Answers1

3

Where you'd typically do this kind of work is in the Form_Load event. For example:

using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            await RefreshDataAsync();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            await RefreshDataAsync();
        }

        private async Task RefreshDataAsync()
        {
            button1.Enabled = false;
            listBox1.Items.Clear();

            try
            {
                var data = await GetDataFromDataSourceAsync();
                foreach(var item in data)
                {
                    listBox1.Items.Add(item);
                }
            }
            finally
            {
                button1.Enabled = true;
            }
        }
    }
}

So you'd create a "refresh data" method, and have your Form_Load event call that. Since you segregated the refresh code, you could have other things call it as well, such as a button.

WinForm events such as Form_Load or button click events can be made asynchronous by simply adding the async keyword to them. More info about that here.

Andy
  • 12,859
  • 5
  • 41
  • 56