我如何".Wait()"?在ConfiguredTaskAwaitable上? [英] How do I ".Wait( )" on a ConfiguredTaskAwaitable?
问题描述
给出以下扩展名以防止Tasks
阻止UI线程(可能不是确切的正确术语,而是其他):
Given the following extension to prevent Tasks
from blocking the UI Thread ( probably not the exact correct terminology but whatever ) :
public static ConfiguredTaskAwaitable DontBlock( this Task T ) {
return T.ConfigureAwait( false );
}
public static ConfiguredTaskAwaitable<T> DontBlock<T>( this Task<T> T2 ) {
return T2.ConfigureAwait( false );
}
在某些情况下(例如,如果我需要在对象构造函数中调用awaitable,或者需要从WinForms Program.Main( )
方法中调用.Wait( )
),则需要执行以下操作:
In some cases ( such as if I need to call an awaitable within an object constructor, or if I need to call .Wait( )
from a WinForms Program.Main( )
method), I need to do the following :
public class Foo{
public Foo( ){
//I know full well that the result from DontBlock does not have a 'wait' method, so of course this will fail miserably.
AwaitableBar.DontBlock( ).Wait( );
}
}
如果我不能在async
函数/方法上调用它,该如何在async
函数/方法之外等待"它?我看到它有一个.GetAwaiter( )
方法,该方法返回一个ConfiguredTaskAwaiter
对象,但是我不知道该怎么做,而Google又使我失败了...我应该在返回的对象上调用GetResult( )
吗?马上?这样做会等待一切完成,还是跳过它,或者爆炸?
How can I 'await' it outside an async
function/method if I can't call .Wait( )
on it? I see that it has a .GetAwaiter( )
method which returns a ConfiguredTaskAwaiter
object, but I have no idea what to do with it, and Google has failed me again... Am I supposed to call GetResult( )
on the returned object right away? Will doing that wait for everything to finish, or just skip right over it, or explode?
推荐答案
我同意@usr的观点,认为返回ConfiguredTaskAwaitable
并不理想.通常,您的异步方法应返回任务.这是关注点分离的问题.
I agree with the @usr that returning a ConfiguredTaskAwaitable
is not ideal. Generally, your asynchronous methods should return tasks. This is a matter of separation of concerns.
但是,一旦有了ConfiguredTaskAwaitable
,只需调用awaitableObj.GetAwaiter().GetResult()
(或适当的替换项)即可. GetResult()
将阻止.
Once you have a ConfiguredTaskAwaitable
, though, simply call awaitableObj.GetAwaiter().GetResult()
(or the appropriate substitution). GetResult()
will block.
这篇关于我如何".Wait()"?在ConfiguredTaskAwaitable上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!