google-api - Google DriveService C# 泄漏 HttpConnection 对象

标签 google-api google-drive-api google-api-dotnet-client

我有一个使用 C# SDK 来利用 Google Drive 服务的应用程序。我正在使用服务帐户凭据,通过模拟来指定我代表的用户。

我遇到的问题是我需要为每个模拟用户创建一个新的 DriveService,并且每个 DriveService 实例都会创建 2 个 HttpConnection 对象,当我 Dispose() DriveService 时,这些对象不会被清除。我已经在单元测试中复制了这个。我用这种方法创建了 DriveService:

public DriveService GetDriveService(string email)
    {
        var serviceAccountEmail = "service account email";
        var privateKey = "private key";

        var serviceAcctCreds =  new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
        {
            User = email,
            Scopes = "scopes" }), 
        }.FromPrivateKey(privateKey));

        var driveService = new DriveService(new BaseClientService.Initializer
        { 
            HttpClientInitializer = serviceAcctCreds,
            ApplicationName = "app name",
        });

        return driveService;
    }

然后这样使用它:

public async Task DoTheGDriveMemoryTest()
        {
            var userEmails = new List<string>
            {
                 "email1@example.com", "email2@example.com"
            };
            var i = 1;
            while (true)
            {
                foreach (var email in userEmails)
                {
                    //recommend using Fiddler Autoresponders here
                    using (var service = GetDriveService(email))
                    {
                        var request = service.Changes.List("delta id");                        
                        try
                        {
                            var result = await request.ExecuteAsync();
                        }
                        catch (Exception e)
                        {
                            //do nothing
                        }
                    }
                }
            }
        }

这导致内存中保存的 HttpConnection 对象数量不断增加,这些对象未被垃圾收集清除。

最佳答案

如果 DriveService 在幕后使用 HttpClient,您可能会遇到无法处理共享对象的情况,或者连接会一直保持到超时。

But HttpClient is different. Although it implements the IDisposable interface it is actually a shared object.

参见 https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

关于google-api - Google DriveService C# 泄漏 HttpConnection 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53104462/

相关文章:

php - 如何获取事件的创建者?

android - 如何从 Google 云端硬盘中删除文件

google-api - 日历 API v3 - 处理单向同步的已删除事件

c# - 如何安全地存储 google drive api 提供的每个用户的 OAuth 响应文件

asp.net-mvc - Google 日历在 ASP .net 中添加事件 : Auth fail

android - 使用 Amazon Web Services (AWS) 简单通知服务 (SNS) 设置 Google Cloud Messenging (GCM)

java - 从 Oauth2 Google Contacts API 获取用户信息

android - 使用 Google Drive SDK V2 枚举文件夹和文件

java - 将文件保存为 http 响应错误中收到的 .pdf

c# - 谷歌云端硬盘 API v2 : InsertMediaUpload - Null response received