C# 如何在RestSharp中使用ExecuteAsync返回变量

C# 如何在RestSharp中使用ExecuteAsync返回变量,c#,.net,asynchronous,restsharp,C#,.net,Asynchronous,Restsharp,我在异步方法中返回变量时遇到问题。我能够获取要执行的代码,但无法获取返回电子邮件地址的代码 public async Task<string> GetSignInName (string id) { RestClient client = new RestClient("https://graph.windows.net/{tenant}/users"); RestRequest request = new RestRequest($

我在异步方法中返回变量时遇到问题。我能够获取要执行的代码,但无法获取返回电子邮件地址的代码

    public async Task<string> GetSignInName (string id)
    {

        RestClient client = new RestClient("https://graph.windows.net/{tenant}/users");
        RestRequest request = new RestRequest($"{id}");
        request.AddParameter("api-version", "1.6");
        request.AddHeader("Authorization", $"Bearer {token}");
        //string emailAddress = await client.ExecuteAsync<rootUser>(request, callback);

        var asyncHandler = client.ExecuteAsync<rootUser>(request, response =>
        {
            CallBack(response.Data.SignInNames);
        });

        return "test"; //should be a variable
    }
公共异步任务GetSignInName(字符串id)
{
RestClient=新的RestClient(“https://graph.windows.net/{租户}/用户);
RestRequest请求=新的RestRequest($“{id}”);
AddParameter(“api版本”、“1.6”);
AddHeader(“Authorization”,$“Bearer{token}”);
//字符串emailAddress=wait client.ExecuteAsync(请求、回调);
var asynchHandler=client.ExecuteAsync(请求、响应=>
{
回调(response.Data.signNames);
});
返回“test”;//应该是一个变量
}

RestSharp内置了用于执行基于任务的异步模式(TAP)的方法。这是通过
RestClient.ExecuteTaskAsync
方法调用的。这将返回一个响应,
response.Data
属性将具有泛型参数的反序列化版本(在本例中为rootUser)

公共异步任务GetSignInName(字符串id)
{
RestClient=新的RestClient(“https://graph.windows.net/{租户}/用户);
RestRequest请求=新的RestRequest($“{id}”);
AddParameter(“api版本”、“1.6”);
AddHeader(“Authorization”,$“Bearer{token}”);
var response=wait client.ExecuteTaskAsync(请求);
if(response.ErrorException!=null)
{
const string message=“从Windows图形API检索响应时出错。有关详细信息,请检查内部详细信息。”;
var exception=新异常(消息,response.ErrorException);
抛出异常;
}
返回response.Data.Username;
}

请注意,
rootUser
不是C#中类的好名称。我们的常规惯例是使用PascalCase类名称,因此它应该是RootUser。

Mason,谢谢您的回答。这很有帮助。梅森,有没有办法加快速度?它似乎需要10分钟来执行,而以前需要48秒?你必须对它进行分析,并确定减速的原因。单凭这一点不应该让它变慢。
public async Task<string> GetSignInName (string id)
{
    RestClient client = new RestClient("https://graph.windows.net/{tenant}/users");
    RestRequest request = new RestRequest($"{id}");
    request.AddParameter("api-version", "1.6");
    request.AddHeader("Authorization", $"Bearer {token}");        
    var response = await client.ExecuteTaskAsync<rootUser>(request);

    if (response.ErrorException != null)
    {
        const string message = "Error retrieving response from Windows Graph API.  Check inner details for more info.";
        var exception = new Exception(message, response.ErrorException);
        throw exception;
    }

    return response.Data.Username;
}