【问题标题】:Is there any way to use Google Calendar API in C# (WPF) with an async method?有什么方法可以通过异步方法在 C# (WPF) 中使用 Google Calendar API?
【发布时间】:2020-07-24 02:59:33
【问题描述】:

我是初学者,这是 Google 提供的有关如何使用 C# 正式实现 Google 日历 API 的示例。我遇到的问题是现在可以将它与等待/异步一起使用,这意味着我的 WPF 应用程序在发出请求时被冻结(?)。我在谷歌上寻找答案,但找不到与该特定问题相关的任何内容。

using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CalendarQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/calendar-dotnet-quickstart.json
        static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
        static string ApplicationName = "Google Calendar API .NET Quickstart";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List("primary");
            request.TimeMin = DateTime.Now;
            request.ShowDeleted = false;
            request.SingleEvents = true;
            request.MaxResults = 10;
            request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

            // List events.
            Events events = request.Execute();
            Console.WriteLine("Upcoming events:");
            if (events.Items != null && events.Items.Count > 0)
            {
                foreach (var eventItem in events.Items)
                {
                    string when = eventItem.Start.DateTime.ToString();
                    if (String.IsNullOrEmpty(when))
                    {
                        when = eventItem.Start.Date;
                    }
                    Console.WriteLine("{0} ({1})", eventItem.Summary, when);
                }
            }
            else
            {
                Console.WriteLine("No upcoming events found.");
            }
            Console.Read();

        }
    }
}

我需要添加等待/异步,但如果我使方法异步并使其返回任务,它当然不起作用,因为 service.Events.List 没有实现 GetAwaiter:

EventsResource.ListRequest request = await service.Events.List("primary"); // this is what i would need

我想替代方案是使用纯 REST api,但真的没有其他方法吗?

【问题讨论】:

标签: c# wpf google-calendar-api


【解决方案1】:

Main变成async,避免.Result

static async Task Main(string[] args)
{
    //...
            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true));
    // ...
}

要将常规同步方法转换为等待操作,您可以尝试Task.Run()

EventsResource.ListRequest request = await Task.Run(() => service.Events.List("primary"));

【讨论】:

  • 你不知道这对我有多大帮助,谢谢!
猜你喜欢
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 2011-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多