I need to show a form and at the same time upload some data. I'm looking at how to do it with async
and await
, but I'm still blocking the UI.
Here's my code:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Async
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public async void Init()
{
Text = "Setting Form Caption";
label1.Text = "Setting label1 text";
label2.Text = "Setting label2 text";
var res = await GetData();
res.ForEach(r => listBox1.Items.Add(r));
}
async Task<List<int>> GetData()
{
await Task.Delay(200);
List<int> lTmp = new List<int>();
await Task.Run(() =>
{
foreach (var t in Enumerable.Range(1, 10000))
lTmp.Add(t);
});
return lTmp;
}
}
}
This code is called at Button click inside another form with this code:
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.Init();
frm.Show();
}
Executing this, I have 2 questions:
- If I remove
Task.Delay(200)
from theGetData()
method, I can't see the text of the labels until the data has finished loading. - I can't move the Form2 until the
GetData()
is finished
Could someone tell me what I am doing wrong?
Or should I take some other approach?