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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With