我刚开始使用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);
}
}
似乎异步任务阻塞并且它不会将控制权返回给调用者,然后保持循环执行。
答案 0 :(得分:3)
正确,你有一个经典的异步阻止另一个异步的情况。 您应该在等待ScannedCode.AddAsync()时将ConfigureAwait设置为false;
public Node removeKthFromLast(Node head, int k) {
int n;
Node p = head;
for (n=0;head != null;n++) {
p = head.next;
}
return removeKthFromLastAux(head, n-k);
}
private Node removeKthFromLastAux(Node head, int ik) {
if (head == null) {
return null;
}
if (ik == 0) {
return head.next;
}
head.next = removeKthFromLastAux(head, ik-1);
return head;
}
这使得它在线程池线程而不是ASP.NET请求上下文中恢复。
您可以阅读以下文章http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html,该文章解释了这一点以及使用异步代码时的其他最佳做法。