Task.Run 应该如何调用 VB.NET 中的异步方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42009868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How should Task.Run call an async method in VB.NET?
提问by Mike Henry
Given an asynchronous method that does both CPU and IO work such as:
给定一个同时执行 CPU 和 IO 工作的异步方法,例如:
Public Async Function RunAsync() As Task
DoWork()
Await networkStream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(False)
End Function
Which of the following options is the best way to call that asynchronous method from Task.Run in Visual Basic and why?
以下哪个选项是从 Visual Basic 中的 Task.Run 调用该异步方法的最佳方法,为什么?
Which is the VB equivalent for C# Task.Run(() => RunAsync())?
哪个是 C# 的 VB 等价物Task.Run(() => RunAsync())?
Await Task.Run(Function() RunAsync())
' or
Await Task.Run(Sub() RunAsync())
Are the Async/Await keywords within Task.Run necessary or redundant? This commentclaims they're redundant, but this answersuggests it might be necessary in certain cases:
Task.Run 中的 Async/Await 关键字是必要的还是多余的?此评论声称它们是多余的,但此答案表明在某些情况下可能有必要:
Await Task.Run(Async Function()
Await RunAsync()
End Function)
Is ConfigureAwait useful within Task.Run?
在 Task.Run 中 ConfigureAwait 有用吗?
Await Task.Run(Function() RunAsync().ConfigureAwait(False))
Await Task.Run(Async Function()
Await RunAsync().ConfigureAwait(False)
End Function)
Which of the above 5 Task.Run options is best practice?
以上 5 个 Task.Run 选项中的哪一个是最佳实践?
Note: There's a similar question How to call Async Method within Task.Run?but it's for C#, the selected answer has negative votes, and doesn't address ConfigureAwait.
注意:有一个类似的问题如何在 Task.Run 中调用异步方法?但它是针对 C# 的,选定的答案有反对票,并且没有解决 ConfigureAwait。
回答by Stephen Cleary
Which is the VB equivalent for C#
Task.Run(() => RunAsync())?
哪个是 C# 的 VB 等价物
Task.Run(() => RunAsync())?
My VB is horribly rusty, but it should not be the Subone, so I'd go with:
我的 VB 非常生锈,但它不应该是那个Sub,所以我会选择:
Task.Run(Function() RunAsync())
Are the Async/Await keywords within Task.Run necessary or redundant?
Task.Run 中的 Async/Await 关键字是必要的还是多余的?
I have a blog post on the subject. In this case, they're redundant because the delegate is trivial.
我有一篇关于这个主题的博客文章。在这种情况下,它们是多余的,因为委托是微不足道的。
Is ConfigureAwait useful within Task.Run?
在 Task.Run 中 ConfigureAwait 有用吗?
Only if you do an Await.
只有当你做一个Await.

