問題描述
我發現自己想要實現一個 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 returnsvoid
, 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 forvoid
tasks, by using something like aTaskCompletionSource<bool>
(and exploit the fact that theTask<bool>
is also an untypedTask
).這篇關于AsyncCTP:創建一個 IAwaitable 的類的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持! - A
- 一個