我发现自己想要实现一个 IAwaitable 类(实现异步调用而不阻塞线程的东西)。
我已经安装了最新版本的 AsyncCTP,编译器表示我需要 IsCompleted() 成员。好的,CTP 预览已经向前推进了一点(我明白了,就像预览一样)
问题:AsyncCTP 语言扩展现在需要什么接口?
问题:在这一切中,我假设我可以通过 lamda/delegate 向“IAwaitable”发出信号?这可能吗?我们调用 EndAwait 吗?智能感知建议您调用 EndAwait 来检索结果......所以这听起来不对。有什么想法吗?
到目前为止我找到的所有示例都是针对 AsyncCTP 库已经实现的功能,例如:
await new WebClient().DownloadStringTaskAsync(uri).ConfigureAwait(false);
来自 101 AsyncSamplesCS
背景:
我发现自己在 Jon Skeets 页面上(再次)查看
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;
}
}
I found myself wanting to implement an IAwaitable class (something that implements asynchronous calls without blocking threads).
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)
Question: What interface are the AsyncCTP language extensions expecting now?
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?
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);
from the 101 AsyncSamplesCS
Background:
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;
}
}
发布评论
评论(1)
随着 SP1 刷新,您需要:
GetAwaiter()
方法(可能但不一定是扩展方法),该方法返回某些内容(示例中的Awaiter
),其中包含以下所有内容:bool IsCompleted
属性 (get
)void OnCompleted(操作回调)
GetResult()
方法,返回void
或等待操作的所需结果但是,我建议您查看
TaskCompletionSource
- 我看了这个,它的表现优于我天真的实现(此处已过时)。您还可以将其用于void
任务,方法是使用TaskCompletionSource
之类的东西(并利用Task
也是一个无类型的Task
)。With the SP1 refresh, you need:
GetAwaiter()
method (possibly but not necessarily an extension method) that returns something (Awaiter
in your example) with all of:bool IsCompleted
property (get
)void OnCompleted(Action callback)
GetResult()
method which returnsvoid
, or the desired outcome of the awaited operationHowever, 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 forvoid
tasks, by using something like aTaskCompletionSource<bool>
(and exploit the fact that theTask<bool>
is also an untypedTask
).