简体   繁体   中英

how do I return values from a `async Task` function?

I need to return the value submitOut from async Task testWCF2 function below?Can anyone provide guidance on how to do it?

    public static async Task testWCF2(string xmlConfig)
    {
        string submitOut;

        using (var client = new System.Net.Http.HttpClient())
        {
            var url = "http://server:8100/api/SoftwareProductBuild";
            var content = new StringContent(xmlConfig, Encoding.UTF8, "application/xml");
            var response = await client.PostAsync(url, content);
            if (response.IsSuccessStatusCode)
            {
                var responseBody = await response.Content.ReadAsStringAsync();
                submitOut = responseBody;
            }
            else
            {
                submitOut = string.Format("Bad Response {0} \n", response.StatusCode.ToString());
                submitOut = submitOut + response;
            }
        }
    }

    public string QlasrSubmit(List<XMLSiInfo> xmlConfigs)
    {
        string submitOut = "QLASR: ";

        foreach (XMLSiInfo xmlConfig in xmlConfigs)
        {
            submitOut = submitOut + "\n" + testWCF2(xmlConfig.xml).ToString();
        }

        return submitOut;
    }

    public string QlasrPostcommit(string si, string sp, string variant = null)
    {
        .............
        string submitStatus            = QlasrSubmit(siInfo);
        ....
        return submitStatus;
    }

Change your return type to Task<string> , as such:

public static async Task<string> testWCF2(string xmlConfig)

Then you can just return submitOut;

Once you are returning a value, then you consume it using await :

public async Task<string> QlasrSubmit(List<XMLSiInfo> xmlConfigs)
{
  string submitOut = "QLASR: ";

  foreach (XMLSiInfo xmlConfig in xmlConfigs)
  {
    submitOut = submitOut + "\n" + await testWCF2(xmlConfig.xml);
  }

  return submitOut;
}

I recommend reading up on the basics of async .

public static async Task<string> testWCF2(string xmlConfig)
{
    string submitOut;

    using (var client = new System.Net.Http.HttpClient())
    {
        var url = "http://server:8100/api/SoftwareProductBuild";
        var content = new StringContent(xmlConfig, Encoding.UTF8, "application/xml");
        var response = await client.PostAsync(url, content);
        if (response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            submitOut = responseBody;
        }
        else
        {
            submitOut = string.Format("Bad Response {0} \n", response.StatusCode.ToString());
            submitOut = submitOut + response;
        }
    }

    return submitOut;
}

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