简体   繁体   English

C#FetchAsync和委托方法调用

[英]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();
                        }
                    });
        }

I want to call now FetchAsync but I don't know how 我想现在调用FetchAsync但我不知道如何

service.Userinfo.Get().FetchAsync(new ExecuteRequestDelegate<Userinfo>() {...});

and I get back that ExecuteRequestDelegate does not contain an constructor that takes 0 arguments. 我得到的回复是ExecuteRequestDelegate不包含一个带0参数的构造函数。

What can I do? 我能做什么? I want to get Userinfo data? 我想获取Userinfo数据?

FetchAsync 's parameter is a method that accepts a LazyResult as it's only parameter and that returns void . FetchAsync的参数是一个接受LazyResult作为唯一参数并返回void This is consistent with the general patter of a "callback" method, which is one way of writing an asynchronous method. 这与“回调”方法的一般模式一致,这是编写异步方法的一种方式。 In order to be asynchronous this method will return immediately after being called, and when the operation it logically represents actually finishes, it will call your callback method, passing in the results of the asynchronous operation as the parameter to the callback. 为了异步,这个方法会在被调用后立即返回,当逻辑上表示的操作实际完成时,它将调用你的回调方法,将异步操作的结果作为参数传递给回调。

While you could write out a named method to handle this case, it's often appropriate to use a lambda here: 虽然你可以写出一个命名方法来处理这种情况,但在这里使用lambda通常是合适的:

service.Userinfo.Get().FetchAsync(
    lazyResult => Console.WriteLine(lazyResult.Result));

If you have more than a line or so of code, then it's worth taking the time to use a named method: 如果你有一行以上的代码,那么值得花时间使用一个命名方法:

public void ProcessResult(LazyResult<Userinfo> result)
{
    //Do stuff
}

service.Userinfo.Get().FetchAsync(ProcessResult);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM