[英]C# FetchAsync and delegate call in method
/// <summary>
/// Delegate for executing an asynchronous request.
/// </summary>
public delegate void ExecuteRequestDelegate<T>(LazyResult<T> response);
public void FetchAsync([Optional] ExecuteRequestDelegate<TResponse> methodToCall)
{
GetAsyncResponse(
(IAsyncRequestResult state) =>
{
var result = new LazyResult<TResponse>(() =>
{
// Retrieve and convert the response.
IResponse response = state.GetResponse();
return FetchObject(response);
});
// Only invoke the method if it was set.
if (methodToCall != null)
{
methodToCall(result);
}
else
{
result.GetResult();
}
});
}
我想現在調用FetchAsync
但我不知道如何
service.Userinfo.Get().FetchAsync(new ExecuteRequestDelegate<Userinfo>() {...});
我得到的回復是ExecuteRequestDelegate不包含一個帶0參數的構造函數。
我能做什么? 我想獲取Userinfo
數據?
FetchAsync
的參數是一個接受LazyResult
作為唯一參數並返回void
。 這與“回調”方法的一般模式一致,這是編寫異步方法的一種方式。 為了異步,這個方法會在被調用后立即返回,當邏輯上表示的操作實際完成時,它將調用你的回調方法,將異步操作的結果作為參數傳遞給回調。
雖然你可以寫出一個命名方法來處理這種情況,但在這里使用lambda通常是合適的:
service.Userinfo.Get().FetchAsync(
lazyResult => Console.WriteLine(lazyResult.Result));
如果你有一行以上的代碼,那么值得花時間使用一個命名方法:
public void ProcessResult(LazyResult<Userinfo> result)
{
//Do stuff
}
service.Userinfo.Get().FetchAsync(ProcessResult);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.