繁体   English   中英

任务继续

[英]Task Continuation

我有一个返回人员列表的Web API:

public async Task<HttpResponseMessage> Get()
{
    var people = await _PeopleRepo.GetAll();
    return Request.CreateResponse(HttpStatusCode.OK, people);
}

我有一个控制台应用程序,我希望能够对其进行调用,这样它首先可以吸引人们,然后通过调用ToString()方法遍历他们,然后完成。

我有以下方法来吸引人们:

static async Task<List<Person>> GetAllPeople()
{
    List<Person> peopleList = null;
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:38263/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.GetAsync("People");
        response.EnsureSuccessStatusCode();
        if (response.IsSuccessStatusCode)
        {
            peopleList = await response.Content.ReadAsAsync<List<Person>>();
        }
    }

    return peopleList;
}

然后,我有了第二个功能来打印列表:

static void PrintPeopleList(List<Person> people)
{
    if (people == null)
    {
        Console.Write("No people to speak of.");
        return;
    }

    people.ForEach(m => Console.WriteLine(m.ToString()));
}

我尝试使用任务工厂首先使用GetAllPeople()下载人员列表,然后在响应返回但编译器给出模棱两可的调用错误时,将结果提供给PrintPeopleList():

Task.Factory.StartNew(() => GetAllPeople()).ContinueWith((t) => PrintPeopleList(t.Result));

我要走吗?

刚打电话

List<Person> persons = await GetAllPeople();
PrintPeopleList(persons);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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