Reputation: 1657
Is there any simply way to call my existing void method asynchronously, so that my form show up instantly without waiting for that method to end?
That method reads directory that contains almost 20000 files to array, and populates it to ListView. It takes almost ten seconds when running first time and Windows have not cached it yet.
Upvotes: 0
Views: 112
Reputation: 6849
Try following method
private delegate void AddItem(string item);
private AddItem addListItem;
private void form_load()
{
new System.Threading.Thread(new ThreadStart(this.FillItems)).Start();
}
private void FillItems()
{
addListItem = new AddItem(this.addItem);
///Fill your list here
this.Invoke(addListItem, "ABC");
this.Invoke(addListItem, "XYZ");
this.Invoke(addListItem, "PQR");
}
private void addItem(string item)
{
listView1.Items.Add(item);
}
Upvotes: 0
Reputation: 82136
You can run your code in a new thread so it doesn't block the UI thread, it's pretty trivial to do this using the TPL
Task.Run(() =>
{
// enumerate files
return files;
}).ContinueWith(t =>
{
var files = t.Result;
// update list view
}, TaskScheduler.FromCurrentSynchronizationContext());
Upvotes: 3
Reputation: 460
You can used Task but also return results and use async/await or use dispatcher to update UI.
try
{
var result = await Task.Run(() => GetResult());
// Update UI: success.
// Use the result.
listView.DataSource = result;
listView.DataBind();
}
catch (Exception ex)
{
// Update UI: fail.
// Use the exception.
}
Look at this
Upvotes: 1