簡體   English   中英

在C#中以異步方式創建新的DocumentDB文檔的問題

[英]Problems for create new DocumentDB documents in async in C#

我剛開始使用DocumentDB,所以我下載了.NET SDK。 按照從Azure網站下載的使用示例,我正在嘗試創建一些文檔以保存到DocumentDB。 示例代碼如下

   public static void Main(string[] args)
    {
        try
        {
            GetStartedDemo().Wait();
        }
        catch (DocumentClientException de)
        {
            // omissis
        }
    }
    private static async Task GetStartedDemo()
    {
        var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);

        Family andersonFamily = new Family
        {
            Id = "AndersenFamily",
            LastName = "Andersen",
            Parents = new Parent[] {
                new Parent { FirstName = "Thomas" },
                new Parent { FirstName = "Mary Kay"}
                },
            Children = new Child[] {
                    new Child
                    {
                        FirstName = "Henriette Thaulow",
                        Gender = "female",
                        Grade = 5,
                        Pets = new Pet[] {
                            new Pet { GivenName = "Fluffy" }
                        }
                    }
                },
            Address = new Address { State = "WA", County = "King", City = "Seattle" },
            IsRegistered = true
        };

        await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, andersonFamily);

        client.Dispose();
    }

這段代碼很好用。 我的代碼幾乎相同,除了我將JSON保存到DB中的類。 它總是停在線上

await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + coll.Id, this);

我的整個代碼如下

public static async Task Save(int UserId, int productID, string code, string language, string dataOraLettura, string longitudine, string latitudine, string nazione_lettura)
    {
        CultureInfo ciEN = CultureInfo.GetCultureInfo("en-US");
        CodeType ScannedCode = new CodeType
        {
            Code = code,
            ProductId = productID,
            ScanLog = new List<CodeType.ScanDataType>()
        };
        ScannedCode.ScanLog.Add(new CodeType.ScanDataType
        {
            Location = new Microsoft.Azure.Documents.Spatial.Point(double.Parse(longitudine, ciEN.NumberFormat), double.Parse(latitudine, ciEN.NumberFormat)),
            ScanType = CodeType.ScanDataType.eScanType.Alert,
            UserId = UserId.ToString(),
            TimeStamp = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmssffff"))
        });
        await ScannedCode.AddAsync();

    }

   public async Task AddAsync()
    {
        using (DocumentClient client = new DocumentClient(new Uri(WebConfigurationManager.AppSettings["DbURI"]), WebConfigurationManager.AppSettings["DbKEY"]))
        {
            var CodeDocuments = client.CreateDocumentQuery<CodeType>("dbs/" + database.Id + "/colls/" + coll.Id).Where(a => a.Code == this.Code).ToArray();
            if (CodeDocuments.Length == 0)
                await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + coll.Id, this);
        }
    }

它似乎是異步任務塊,它不會將控制權返回給調用者,然后保持循環執行。

正確,你有一個經典的異步阻止另一個異步的情況。 您應該在等待ScannedCode.AddAsync()時將ConfigureAwait設置為false;

 await ScannedCode.AddAsync().ConfigureAwait(false);

這使它在線程池線程而不是ASP.NET請求上下文上恢復。

您可以閱讀以下文章http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html ,它可以很好地解釋這一點以及使用異步代碼時的其他最佳做法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM