vb.net 如何从非异步方法异步调用异步方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15099742/
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 to call async method asynchronously from non-async method
提问by user1937198
How do you wait on a task from an async method, in a non-async method, without actually calling the method?
您如何在非异步方法中等待来自异步方法的任务,而不实际调用该方法?
Class TestAsync
Dim workevent As New Threading.ManualResetEvent(False)
Sub work()
Dim Task As Task = Test()
'Do Work which affects Test Here
Threading.Thread.Sleep(100)
workevent.Set()
'wait for Test to complete
'Task.Wait() -causes the application to hang
End Sub
Async Function Test() As Task
workevent.WaitOne()
End Function
End Class
回答by svick
First, if possible, never do that. Synchronously waiting for an async method defeats the whole purpose of using async. Instead you should make work()into an Async Function WorkAsync() As Task. And then make the method(s) that call work()asynchronous too, and so on, all the way up.
首先,如果可能,永远不要那样做。同步等待异步方法违背了使用异步的全部目的。相反,您应该制作work()成一个Async Function WorkAsync() As Task. 然后也使调用work()异步的方法,依此类推,一路向上。
Second, asynchronous isn't the same as parallel. If you have Asyncmethod with no Awaits, it will execute completely synchronously, as if it was a normal method. So, your method will hang even without Task.Wait().
其次,异步与并行不同。如果你有Async没有Awaits 的方法,它会完全同步执行,就好像它是一个普通的方法一样。因此,即使没有Task.Wait().
What you can do is to run Test()on a background thread using Task.Run():
您可以做的是Test()使用Task.Run()以下方法在后台线程上运行:
Sub work()
Dim Task As Task = Task.Run(AddressOf Test)
Threading.Thread.Sleep(100)
workevent.Set()
Task.Wait()
End Sub
The Taskreturned from Run()will complete when the Taskreturned from Test()completes.
当Task返回的 fromRun()完成时,Task返回的 from 将Test()完成。
(There are other issues causing hangs when combining Wait()and Async, but they are not relevant in this specific case.)
(在组合Wait()和时还有其他问题会导致挂起Async,但在这种特定情况下它们不相关。)
But I repeat: you shouldn't do this, since it blocks the UI thread, though it's only for a short while.
但我再说一遍:你不应该这样做,因为它会阻塞 UI 线程,尽管它只是一小会儿。

