如果没有 GetAwaiter 方法,我可以等待吗? [英] Can I await something if there's no GetAwaiter method?
问题描述
我看到了一些关于设计自定义等待类型的文章:
I saw some articles about designing a custom awaitable type:
http://books.google.com.br/books?id=1On1glEbTfIC&pg=PA83&lpg=PA83&dq=create+a+custom+awaitable+type
现在考虑下面的例子:
<Button x:Name="BtnA"
Width="75"
Margin="171,128,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="BtnA_Click"
Content="Button A" />
<Button x:Name="BtnB"
Width="75"
Margin="273,128,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Content="Button B" Click="BtnB_OnClick" />
和:
private async void BtnA_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Awaiting Button B..");
var sx = Observable.FromEvent<MouseButtonEventHandler,
MouseButtonEventArgs>(a => (b, c) => a(c),
add => BtnB.PreviewMouseDown += add,
rem => BtnB.PreviewMouseDown -= rem)
.Do(a => a.Handled = true)
.Take(1);
await sx;
MessageBox.Show("Button B Pressed after Button A");
}
private void BtnB_OnClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("Button B Pressed Without Click in Button A");
}
如果没有 GetAwaiter()
方法,为什么我可以 await IObservable
(在这种情况下订阅完成)?
Why can I await IObservable<T>
(in this case when subscription is completed), if there's no GetAwaiter()
method?
是编译器实现的吗?是否有可能实现可以 await
的东西而无需显式此方法(某些情况下正在使用哪些接口)?为什么没有类似的东西:
Is it implemented by the compiler? Is it possible to implement something that can await
without to explicit this method (some scenarios which interfaces is being used)?
And why isn't there something like:
public interface ITask<out T>
{
IAwaiter<T> GetAwaiter();
}
public interface IAwaiter<out T> : ICriticalNotifyCompletion
{
bool IsCompleted { get; }
T GetResult();
}
...还是创建自定义等待的真实接口?
... or real interfaces to create a custom awaitable?
推荐答案
首先,没有.
你不能await
something没有GetAwaiter
方法返回somethingGetResult
、OnCompleted
、IsCompleted
并实现 INotifyCompletion
.
First of all, no.
You can't await
something that doesn't have a GetAwaiter
method that returns something that has GetResult
, OnCompleted
, IsCompleted
and implements INotifyCompletion
.
在实例方法之上,编译器还接受 GetAwaiter
扩展方法.在这种情况下,Reactive Extensions 的 Observable
提供了该扩展:
The compiler, on top of instance methods, also accepts GetAwaiter
extensions methods. In this case Reactive Extensions's Observable
provides that extension:
public static AsyncSubject<TSource> GetAwaiter<TSource>(this IObservable<TSource> source);
例如,这是我们如何使字符串可等待(编译但显然实际上不起作用):
For example, this is how we can make strings awaitable (which compiles but obviously won't actually work):
public static Awaiter GetAwaiter(this string s)
{
throw new NotImplementedException();
}
public abstract class Awaiter : INotifyCompletion
{
public abstract bool IsCompleted { get; }
public abstract void GetResult();
public abstract void OnCompleted(Action continuation);
}
await "bar";
这篇关于如果没有 GetAwaiter 方法,我可以等待吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!