【问题标题】:how to return result from async method cosmodb?如何从异步方法 cosmos db 返回结果?
【发布时间】:2018-02-08 15:09:27
【问题描述】:

在做了一个搜索后,我发现document db api支持分组,所以我使用linq实现了,

如何查看数据酶的结果?

static void Main(string[] args)
        {
            Program p = new Program();
            var result =  p.GetStartedDemo().Wait();
        }

        private async Task GetStartedDemo()
        {
            var client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);
            var documentUri = UriFactory.CreateDocumentCollectionUri("testdb", "retrieve");
            var result = client.CreateDocumentQuery<Login>(documentUri)
                  .Where(i => i.logevent == "success" && i._ts > 1517405472 && i._ts <= 1518010272)
                  .GroupBy(t => t._ts);

            return result;
        }

错误:

var 结果 = p.GetStartedDemo().Wait();

无法分配隐式类型的代码变量。什么问题?

【问题讨论】:

  • Task 意味着该方法不返回值,它只是返回一个告诉您何时完成的任务。 Task 是它应该返回的内容,其中 T 是您要返回的对象的类型
  • 我想查看返回结果的输出。如何做到这一点
  • 我坚持这个,至少指导我
  • 不知道cosmosdb的详细情况,没用过。我在我的手机自动取款机上,所以如果在我的笔记本电脑完成更新之前没有人帮忙,我再看看。听起来你需要学习一下任务和异步编程
  • @Dave,我卡住了

标签: c# linq document azure-cosmosdb


【解决方案1】:

您正在执行任务对象的“等待”方法并尝试将其返回分配给“结果”变量。 如果你检查 Task.Wait() method signature 你会发现它没有回报:

public void Wait();

我是您的示例,您的GetStartedDemo 无需返回任务并成为“异步”,您没有在其中执行任何异步操作。你可以简单地返回你想要的适合调用者方法。

如果你想了解 CosmosDB,我建议查看Microsoft documentation about it

为了使您的代码正常工作,您只需更改方法的返回类型以实际匹配您返回的内容:

// Considering that Login._t is of type "long":
private IEnumerable<IGrouping<long, Login>> GetStartedDemo()
{ /* ... */ }    

然后,在您的 Main 方法中,您可以打印按 Login._t 分组的项目:

    static void Main(string[] args)
    {
        Program p = new Program();
        var result =  p.GetStartedDemo();
        foreach (var group in result)
        {
            Console.WriteLine("Group: " + group.Key);

            foreach (Login login in group)
               Console.WriteLine("    " + login.SomeProperty); // print something from the login object.
        }
    }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 2018-09-01
  • 2019-09-05
  • 2023-03-14
  • 2020-03-15
相关资源
最近更新 更多