【问题标题】:Google Drive SDK thread safetyGoogle Drive SDK 线程安全
【发布时间】:2013-03-15 16:12:51
【问题描述】:

我想在多线程环境中使用 Google Drive SDK。 DriveService 类线程中的函数Files.Insert 是否安全?我在文档中找不到与此相关的任何内容。我什至找不到词 thread 那里。

有人知道 Google SDK 是如何处理多线程的吗?我需要为每个线程创建单独的DriveService 对象吗?

【问题讨论】:

    标签: .net thread-safety google-drive-api


    【解决方案1】:

    我一直在针对我正在开发的使用它的 winforms 应用程序对 Google Drive SDK 进行一些性能测试。我看到这篇文章并意识到我从未想过要检查这个问题,因为我一直认为 API 是线程安全的。所以我进行了一些测试。我一直在对文件重命名方法进行一些性能测试,如下所示:

        public static bool SetFileName(string gFileID, string filename, int attempt)
        {
            File sourcefile;
            File replacement = new File();
            bool save = false;
            replacement.Title = filename;
            replacement.Description = filename;
            try
            {
                FilesResource.PatchRequest request = DriveService.Files.Patch(replacement, gFileID);
                sourcefile = request.Fetch();
            }
            catch (Exception e)
            {
                if (attempt < 10)
                {
                    return SetFileName(gFileID, filename, attempt + 1);
                }
                throw e;
            }
            bool result = sourcefile.Title == replacement.Title & sourcefile.Description == replacement.Description;
            if(!result && attempt<10)
                return SetFileName(gFileID, filename, attempt + 1);
            return result;
        }
    

    我正在运行顺序测试以获取此方法的错误率和执行时间。当我阅读您的帖子时,我决定在后台工作人员上运行测试,以了解该方法在多线程环境中的工作方式。在上面的示例中,DriveService 对象的实例化如下:

        private static DriveService DriveService
        {
            get
            {
                if (_service == null)
                {
                    try
                    {
                        _service = new DriveService(Auth);
                    }
                    catch (Exception)
                    {
                    }
                }
                return _service;
            }
        }
    

    如您所见,我的 DriveService 对象被实例化一次,因此当多个后台工作人员同时运行时,他们都使用同一个 DriveService 实例。我用 1000 个并发线程运行了测试,虽然它确实产生了一些错误,但这些错误都是从谷歌驱动服务器返回的“(500)内部服务器错误”。似乎所有文件名都设置正确,并且所有线程都完成而没有挂起。

    但是,在单独的性能测试中,我尝试确定每次需要时实例化 DriveService 是否存在重大性能问题。所以我修改了我的代码如下:

        private static DriveService DriveService
        {
            get
            {
                return new DriveService(Auth);
            }
        }
    

    我再次运行了一些性能测试,这次是想看看在单个 DriveService 实例和为每个线程创建一个新驱动器实例之间运行 100 个并发线程所花费的时间是否存在显着差异。我没有看到任何显着的性能差异。尽管运行之间存在差异,但在我看来,这些差异与运行 PatchRequest 的服务器端处理时间有关,几乎与您是否在需要时创建 DriveService 的新实例无关。

    我知道这不是确定的,但在我看来,Google Drive SDK 是线程安全的。但是,如果不是,则将其视为不是线程安全的似乎不会出现任何性能问题。

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-21
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 2014-07-22
      相关资源
      最近更新 更多