如果没有GetAwaiter方法,我可以等待吗?

J. *_*non 7 .net c# system.reactive async-await

我看到一些关于设计自定义等待类型的文章:

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" />
Run Code Online (Sandbox Code Playgroud)

和:

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");
}
Run Code Online (Sandbox Code Playgroud)

为什么我await IObservable<T>(在这种情况下订阅完成时),如果没有GetAwaiter()方法?

它是由编译器实现的吗?是否有可能实现一些await无需显式的方法(某些场景正在使用哪种场景)?为什么没有这样的东西:

public interface ITask<out T>
{
    IAwaiter<T> GetAwaiter();
}

public interface IAwaiter<out T> : ICriticalNotifyCompletion
{
    bool IsCompleted { get; }
    T GetResult();
}
Run Code Online (Sandbox Code Playgroud)

...或真正的界面来创建一个等待的自定义?

i3a*_*non 20

首先,没有.

你不能await 什么是没有GetAwaiter返回方法的东西GetResult,OnCompleted,IsCompleted和农具INotifyCompletion.

那么,你怎么能await一个IObservable<T>

在实例方法之上,编译器也接受GetAwaiter扩展方法.在这种情况下,Reactive Extensions Observable提供了该扩展:

public static AsyncSubject<TSource> GetAwaiter<TSource>(this IObservable<TSource> source);
Run Code Online (Sandbox Code Playgroud)

例如,这就是我们如何使字符串等待(编译但显然不会实际工作):

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);
}
Run Code Online (Sandbox Code Playgroud)

await "bar";
Run Code Online (Sandbox Code Playgroud)