我想通過web服務從數據庫查詢數據。提供的API允許發送批量請求,以便在一個HTTP請求中發送多個請求。我想從中受益,並試圖通過使用異步代碼和任務構建一個C#接口來使用此服務。如何從其他功能完成任務?
我的目標是要實現類似如下:API的
// Service class that abstracts the server interface.
class Service
{
// Return all StateA objects at the next server contact.
public Task<IEnumerable<StateA>> GetStatesA() { ... }
// Return all StateB objects at the next server contact.
public Task<IEnumerable<StateB>> GetStatesB() { ... }
// Send all queued requests to the server.
public Task SendRequests() { ... }
}
用法:
// Query all StateA and StateB objects from the database and
// process them as soon as they arrive.
service.GetStatesA().ContinueWith((t) => DoSomething(t.Result));
service.GetStatesB().ContinueWith((t) => DoSomething(t.Result));
// Some other code
// Actually access the API such that the data is queried and the Tasks completed.
service.SendRequests();
從我所知,在C#中的任務只能包裹同步功能和返回時,他們完成。有沒有辦法從外部完成任務?
我正在尋找類似於Dart中的Completer類(請參閱https://api.dartlang.org/1.13.0/dart-async/Completer-class.html)。
我建議的一件事就是不要返回任務>。相反,返回一個物化列表......就我個人而言,當嘗試組合迭代器的延遲執行和異步/等待狀態機時,我遇到了意想不到的結果。 http://ctigeek.net/using-asyncawait-with-ienumerable-and-yield-return/ –