简体   繁体   中英

Calling method asynchronously

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.

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());

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM