c# - 如何从同步创建异步方法

标签 c# vb.net async-await

(下面是 C# 代码)

我只是想了解 Async 和 Await。我检查了一些文章和教程,我认为我已经了解了其背后的概念,但在实现一些实际示例时我似乎遇到了困难。

这是我的 UI 类的 New():

Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    PopulateUI()

End Sub

...所以这里的关键是PopulateUI()。我想在不阻塞 UI 的情况下使用此功能。

我提出的编译器可以接受的唯一选项是:

Private Async Sub PopulateUI()
    Await Task.Run(Sub()
            ' Do some stuff that populates the UI comboboxes
        End Sub)
End Sub

...这个选项不起作用,我认为这是因为 Task.Run 在不同的线程中运行,所以更新组合框时会发生奇怪的事情(抱歉,描述如此模糊,我真的不知道更好)。

所以我找到了a similar SO question却没有得到任何满意的答案,这让我觉得事情没那么简单。希望我错了。

<小时/>

C# 版本:

public MyUI()
{
    // This call is required by the designer.
    InitializeComponent();

    // Add any initialization after the InitializeComponent() call.
    PopulateUI();
}

Private async void PopulateUI()
{
    await Task.Run(() => 
    {
        // Do some stuff that populates the UI comboboxes
    })
}

最佳答案

The db call should be awaitable, but it would just be changes would be quite costly for me at this point in time... So would it be a terrible idea to perform a Task.Run() of the fetch operation

正如您所指出的,理想的解决方案是使其始终异步。因此,下面的解决方案是一种 hack(以避免过多的代码更改),而不是最佳实践。

也就是说,您可以在这里使用async voidTask.Run;你只需要小心你的异常处理:

private async void PopulateUI()
{
  ... // Load initial view - "Loading..." message or whatever.
  try
  {
    var data = await Task.Run(() => 
    {
      ... // Read data from database.
    });
    ... // Update UI with data.
  }
  catch (Exception ex) // Not a typo. Catch all exceptions.
  {
    ... // Handle error - display message to user or whatever.
  }
}

关于c# - 如何从同步创建异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32035101/

相关文章:

c# - 如何将 datagridview 单元格格式值导出到 Excel?

vb.net - 如何将值传递给两个不同的参数

vb.net - FxCop 或其他实用程序需要 VB.NET 中的内联文档?

xml - vb.net-从XSD创建类并生成xml

async-await - 具有特征的 tokio-async-await

c# - 如何从 C# 中的 dataGridView 更新 mysql 数据库

c# - 通过泛型方法实例化接口(interface)基类

c# - 检测代码中的动态类型?

rust - 我如何从 actix 处理程序中调用固定的 future ?

c# - 没有等待调用的异步/等待