简体   繁体   中英

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

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

and I get back that ExecuteRequestDelegate does not contain an constructor that takes 0 arguments.

What can I do? I want to get Userinfo data?

FetchAsync 's parameter is a method that accepts a LazyResult as it's only parameter and that returns 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:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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