无法使用Async DocumentDB操作CreateDocumentAsync的结果

时间:2015-05-11 07:00:24

标签: c# azure async-await task-parallel-library azure-cosmosdb

我在Azure上创建了一个documentDB,可以成功创建和获取文档。

但是,虽然在DB中成功创建了文档,但我无法使用CreateDocumentAsync的响应。代码立即返回到控制器上的调用方法。所以永远不会到达调试行。

此外,我将id设置为guid,但返回给控制器的Document的Id为1.

控制器

    [HttpPost]
    [Route("")]
    public IHttpActionResult CreateNewApplication(dynamic data)
    {
        if (data == null)
        {
            return BadRequest("data was empty");
        }

        try
        {
            var doc = _applicationResource.Save(data);
            return Ok(doc.Id); //code hits this point and 'returns'
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

资源

  public async Task<Document> Save(dynamic application)
    {
        Document created;

        using (Client)
        {
            application.id = Guid.NewGuid();
            var database = await RetrieveOrCreateDatabaseAsync(Database);
            var collection = await RetrieveOrCreateCollectionAsync(database.SelfLink, CollectionName);

            //persist the documents in DocumentDB
            created = await Client.CreateDocumentAsync(collection.SelfLink, application);

        }

        Debug.WriteLine("Application saved with ID {0} resourceId {1}", created.Id, created.ResourceId);

        return created;

    }

获取请求按预期返回数据:

    [HttpGet]
    [Route("{id}")]
    public IHttpActionResult GetApplication(string id)
    {
        var application = _applicationResource.GetById(id);
        return Ok(application);
    }

1 个答案:

答案 0 :(得分:3)

那是因为您没有等待异步方法:

此:

var doc = _applicationResource.Save(data);

需要:

var doc = await _applicationResource.Save(data);

您的方法应如下所示:

[HttpPost]
[Route("")]
public async Task<IHttpActionResult> CreateNewApplication(dynamic data)
{
    if (data == null)
    {
        return BadRequest("data was empty");
    }

    try
    {
        var doc = await _applicationResource.Save(data);
        return Ok(doc.Id); //code hits this point and 'returns'
    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }
}