简体   繁体   English

异步调用方法

[英]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? 有没有一种简单的方法可以异步调用我现有的void方法,从而使表单立即显示而无需等待该方法结束?

That method reads directory that contains almost 20000 files to array, and populates it to ListView. 该方法读取包含将近20000个文件的目录的数组,并将其填充到ListView。 It takes almost ten seconds when running first time and Windows have not cached it yet. 第一次运行时将花费近十秒钟,而Windows尚未对其进行缓存。

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 您可以在新线程中运行代码,这样它就不会阻塞UI线程,使用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. 您可以使用Task,也可以返回结果,并使用async / await或使用分派器来更新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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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