gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:12:11 25 4
gpt4 key购买 nike

(下面是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com