From ac7977c16f6d4c7d48ad3c624b6d5caa46c4447f Mon Sep 17 00:00:00 2001
From: Nikolche Kolev <nikolce1kolev@gmail.com>
Date: Mon, 13 Mar 2023 13:56:41 -0700
Subject: [PATCH] Safe ApexTestContext dispose (#5082)

---
 .../NuGet.Tests.Apex/Apex/ApexTestContext.cs   | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)

diff --git a/test/NuGet.Tests.Apex/NuGet.Tests.Apex/Apex/ApexTestContext.cs b/test/NuGet.Tests.Apex/NuGet.Tests.Apex/Apex/ApexTestContext.cs
index 7b63d3df7b5..0b6d18ab281 100644
--- a/test/NuGet.Tests.Apex/NuGet.Tests.Apex/Apex/ApexTestContext.cs
+++ b/test/NuGet.Tests.Apex/NuGet.Tests.Apex/Apex/ApexTestContext.cs
@@ -2,6 +2,8 @@
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System;
+using System.Threading;
+using Microsoft.Build.Utilities;
 using Microsoft.Test.Apex.VisualStudio;
 using Microsoft.Test.Apex.VisualStudio.Solution;
 using NuGet.Common;
@@ -52,8 +54,20 @@ public ApexTestContext(VisualStudioHost visualStudio, ProjectTemplate projectTem
         public void Dispose()
         {
             _logger.LogInformation("Test complete, closing solution.");
-
-            SolutionService.SaveAndClose();
+            for (int attempt = 1; attempt <= 3; attempt++)
+            {
+                try
+                {
+                    SolutionService.SaveAndClose();
+                    break;
+                }
+                catch (Exception ex)
+                {
+                    _logger.LogInformation($"Failed to close VS on dispose. Attempt #{attempt}");
+                    Thread.Sleep(TimeSpan.FromSeconds(3));
+                    ExceptionUtilities.LogException(ex, _logger);
+                }
+            }
             _pathContext.Dispose();
         }
     }