AsyncCTP:创建一个 IAwaitable 的类

AsyncCTP: Creating a class that is IAwaitable(AsyncCTP:创建一个 IAwaitable 的类)

本文介绍了AsyncCTP:创建一个 IAwaitable 的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己想要实现一个 IAwaitable 类(实现异步调用而不阻塞线程的东西).

I found myself wanting to implement an IAwaitable class (something that implements asynchronous calls without blocking threads).

我安装了最新版本的 AsyncCTP,编译器说我需要一个 IsCompleted() 成员.好的,所以 CTP 预览已经移动了一点(我明白了,就像预览一样)

I've got the most recent version of AsyncCTP installed, and the compiler is saying that I need an IsCompleted() member. Okay, so the CTP preview has moved on a little bit (I get that, like it's a preview)

问题:现在AsyncCTP 语言扩展期望什么接口?

Question: What interface are the AsyncCTP language extensions expecting now?

问题: 在所有这些中,我假设我可以通过 lamda/delegate 向IAwaitable"发出信号?这可能吗?我们叫 EndAwait 吗?智能感知建议您调用 EndAwait 来检索结果......所以这听起来不对.有什么想法吗?

Question: In all this I'm assuming that I can signal to the "IAwaitable" via a lamda/delegate? Is this possible? Do we call EndAwait? The intellisense suggests that you call EndAwait to retrieve the result... so that doesn't sound right. Any ideas?

到目前为止,我发现的所有示例都针对 AsyncCTP 库已经实现的功能,例如:

All of the examples I've found so far are for features that the AsyncCTP library has already implemented such as:

  await new WebClient().DownloadStringTaskAsync(uri).ConfigureAwait(false);

来自 101 AsyncSamplesCS

背景:

我发现自己在 Jon Skeets 页面上(再次)查看 这个例子

I find myself on Jon Skeets page (again) looking at this example

using System;

class Test
{
    static async void Main()
    {
        await new Awaitable();
    }
}

class Awaitable
{
    public Awaiter GetAwaiter()
    {
        return new Awaiter();
    }
}

class Awaiter
{
    public bool BeginAwait(Action continuation)
    {
        return false;
    }

    public int EndAwait()
    {
        return 1;
    }
}

推荐答案

随着 SP1 的更新,您需要:

With the SP1 refresh, you need:

  • 某些 GetAwaiter() 方法(可能但不一定是扩展方法)返回某些内容(在您的示例中为 Awaiter),其中包含以下所有内容:
    • 一个 bool IsCompleted 属性 (get)
    • A void OnCompleted(Action callback)
    • 一个 GetResult() 方法,它返回 void,或等待操作的期望结果
    • Some GetAwaiter() method (possibly but not necessarily an extension method) that returns something (Awaiter in your example) with all of:
      • A bool IsCompleted property (get)
      • A void OnCompleted(Action callback)
      • A GetResult() method which returns void, or the desired outcome of the awaited operation

      但是,我建议您查看TaskCompletionSource - 我看了这个,结果出来了- 执行我的幼稚实现(此处;已过时).你也可以将它用于 void 任务,通过使用类似 TaskCompletionSource 的东西(并利用 Task也是一个无类型的Task).

      However, I suggest you look at TaskCompletionSource<T> - I looked at this, and it out-performed my naive implementation (here; obsolete). You can also use it for void tasks, by using something like a TaskCompletionSource<bool> (and exploit the fact that the Task<bool> is also an untyped Task).

      这篇关于AsyncCTP:创建一个 IAwaitable 的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:AsyncCTP:创建一个 IAwaitable 的类

基础教程推荐