Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get returned value of async Task<string> method name()?

I'm trying to get the return string of my method but the problem is I don't know how can I get the return value from public async Task<string> Login(string username, string password, string site).

This is my codes from 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();
}

This is my codes from 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;
}
like image 355
Leonel Sarmiento Avatar asked Oct 09 '14 01:10

Leonel Sarmiento


People also ask

Can async method have return value?

Async methods can have the following return types: Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value. void , for an event handler.

What is async return method?

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

How do I return a task object in C#?

The recommended return type of an asynchronous method in C# is Task. You should return Task<T> if you would like to write an asynchronous method that returns a value. If you would like to write an event handler, you can return void instead. Until C# 7.0 an asynchronous method could return Task, Task<T>, or void.

What is task string in C#?

A task is an object that represents some work that should be done. The task can tell you if the work is completed and if the operation returns a result, the task gives you the result.


1 Answers

Currently you're just calling Wait() - that will block until the task completes, but won't give you the return value. If you use the Result property instead, that will block and then give you the result:

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

Now, that will work in a console app because there's no SynchronizationContext... which means continuations in the async method will be executed on a thread pool thread. If you use the same code from a WinForms UI thread (for example) then you'd end up with a deadlock - the UI thread would be waiting for the task to complete, but the task couldn't complete until it got onto the UI thread to execute some more code.

As an aside, this appears to be storing SabaCertificate and SabaModel in the SabaController, but it's not obvious that it should be doing that.

like image 118
Jon Skeet Avatar answered Oct 09 '22 16:10

Jon Skeet