如何获取异步任务的返回值<string> methdoName()?</string>

时间:2014-10-09 01:45:04

标签: c# asp.net async-await console-application

我正在尝试获取方法的返回字符串,但问题是我不知道如何从public async Task<string> Login(string username, string password, string site)获取返回值。

这是我在Program.cs中的代码

static void Main(string[] args)
{
    var username = "Leonel.Sarmiento";
    var password = "welcome";
    var site = "QADBSite";
    var url = "na1.sabacloud.com";
    ConsoleCustomizer.Spinner Spinner = new ConsoleCustomizer.Spinner("+", "x", "+", "x");
    ConsoleCustomizer.TypeWriter TypeWriter = new ConsoleCustomizer.TypeWriter(15, 150);
    ConsoleCustomizer.Alerts Alerts = new ConsoleCustomizer.Alerts();
    Alerts.Write("Information", "HOST URL:", null);
    TypeWriter.WriteLine(@"http:\\"+url);
    Alerts.Write("Information", "USERNAME:", null);
    TypeWriter.WriteLine(username);
    Alerts.Write("Information", "PASSWORD:", null);
    for (var i = 0; i < password.Length; i++)
    {
        TypeWriter.Write("*");
    }
    Console.WriteLine("");
    SabaController saba = new SabaController(url);
    //var certificate = saba.Login(username, password, site).Wait();
    saba.Login(username, password, site).Wait();
    Console.Read();
}

这是来自Saba Controller.cs的代码

public async Task<string> Login(string username, string password, string site)
{
    using(var client = new HttpClient())
    {
        client.BaseAddress = new Uri("https://" + HostURL + "/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("user", username);
        client.DefaultRequestHeaders.Add("password", password);
        client.DefaultRequestHeaders.Add("site", site);
        //HTTP GET: saba/api/login
        HttpResponseMessage response = await client.GetAsync("Saba/api/login");
        if (response.IsSuccessStatusCode)
        {
            SabaModel saba = await response.Content.ReadAsAsync<SabaModel>();
            SabaCertificate = saba.Certificate;
        }
    }
    return SabaCertificate;
}

1 个答案:

答案 0 :(得分:11)

目前您只是致电Wait() - 这将阻止任务完成,但不会给您返回值。如果您使用Result属性,那将阻止然后给您结果:

string certificate = saba.Login(username, password, site).Result;

现在,这将在控制台应用程序中运行,因为没有SynchronizationContext ...这意味着异步方法中的延续将在线程池线程上执行。如果您使用WinForms UI线程中的相同代码(例如),那么您最终会遇到死锁 - UI线程将等待任务完成,但任务无法完成,直到它完成进入UI线程以执行更多代码。

顺便说一下,这似乎是在SabaCertificate中存储SabaModelSabaController,但 这样做。