Web服务上的返回对象任务

时间:2014-10-22 23:17:22

标签: asp.net-mvc web-services asynchronous asp.net-web-api

我正在尝试调用一个应该运行异步任务的Web服务。此异步任务应迭代记录数组并处理它们。要处理的每条记录都会生成结果。我想要的是在列表中连接这些结果。当调用Web服务时,我想从调用者的HttpResponse中检索这样的列表,但我不知道该怎么做。

来电者功能的代码是:

private void ProcessRecords(List<Record> recordList)
    {
                //The WS is called and a response is awaited
                HttpResponseMessage response = client.PostAsJsonAsync("/api/mycontroller/myws/", recordList).Result;                    
                //TODO: Read the result list from the http response
    }

我的Web服务代码如下:

    [HttpPost]
    [Route("myws")]
    public async Task<IHttpActionResult> WebServiceMethod()
    {
        var jsonString = await Request.Content.ReadAsStringAsync();
        List<Record> recordList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Record>>(jsonString); 
        Task<Result> resultTask = CreateTaskToProcessRecords(recordList);

        //TODO I Do not now what to return here in order 
        //for it to contain the resultTask variable and later await it in the user function
    }

private Task<List<Result>> CreateTaskToProcessRecords(List<Record> recordList)
    {   
        var newTask = Task.Run<List<Result>>(() =>
        {
            List<Result> resultList = new List<Result>();
            try
            {
                foreach(Record record in recordList)
                {
                 var result = DoSomething(record);
                 resultList.Add(result);
                }
                return resultList;
            }
            catch (Exception ex)
            {
                return resultList;
            }
        });
        return newTask;
    }

我要做的是以某种方式返回任务&gt;调用Web服务的函数,以便在Web服务“newTask”中完成的整个处理保持异步。 你有什么想法? 谢谢 路易斯。

1 个答案:

答案 0 :(得分:0)

你所有的工作都是同步的。此处不需要asyncawait,因此请勿使用它们。 (作为一般规则,请避免在ASP.NET上使用Task.Run

[HttpPost]
[Route("myws")]
public IHttpActionResult WebServiceMethod()
{
    var jsonString = await Request.Content.ReadAsStringAsync();
    List<Record> recordList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Record>>(jsonString);
    var results = ProcessRecords(recordList);
    return Json(results);
}

private List<Result> ProcessRecords(List<Record> recordList)
{   
    List<Result> resultList = new List<Result>();
    try
    {
        foreach(Record record in recordList)
        {
             var result = DoSomething(record);
             resultList.Add(result);
        }
        return resultList;
    }
    catch (Exception ex)
    {
        return resultList;
    }
}

请注意,您仍然可以在客户端上异步使用它:

private async Task ProcessRecordsAsync(List<Record> recordList)
{
    // The WS is called and a response is awaited
    HttpResponseMessage response = await client.PostAsJsonAsync("/api/mycontroller/myws/", recordList);
    var result = await response.Content.ReadAsAsync<List<Result>>();
}