Skip to content

Commit 6b56301

Browse files
dispose part 3
1 parent 6a0cca6 commit 6b56301

27 files changed

+153
-95
lines changed

src/Build/BackEnd/BuildManager/LegacyThreadingData.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ internal int MainThreadSubmissionId
8383
/// Given a submission ID, assign it "start" and "finish" events to track its use of
8484
/// the legacy thread.
8585
/// </summary>
86-
[SuppressMessage("Microsoft.Naming", "CA2000:Dispose objects before losing scope", Justification = "The events are disposed in UnregisterSubmissionForLegacyThread")]
86+
[SuppressMessage("Microsoft.Dispose", "CA2000:Dispose objects before losing scope", Justification = "The events are disposed in UnregisterSubmissionForLegacyThread")]
8787
internal void RegisterSubmissionForLegacyThread(int submissionId)
8888
{
8989
lock (_legacyThreadingEventsLock)

src/Deprecated/Engine/Engine/IntrinsicFunctions.cs

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -197,26 +197,34 @@ internal static object GetRegistryValueFromView(string keyName, string valueName
197197
// of that error.
198198
RegistryView view = (RegistryView)Enum.Parse(typeof(RegistryView), viewAsString, true);
199199

200-
using (RegistryKey key = GetBaseKeyFromKeyName(keyName, view, out subKeyName))
200+
RegistryKey key = null;
201+
try
201202
{
202-
if (key != null)
203+
using (key = GetBaseKeyFromKeyName(keyName, view, out subKeyName))
203204
{
204-
using (RegistryKey subKey = key.OpenSubKey(subKeyName, false))
205+
if (key != null)
205206
{
206-
// If we managed to retrieve the subkey, then move onto locating the value
207-
if (subKey != null)
207+
using (RegistryKey subKey = key.OpenSubKey(subKeyName, false))
208208
{
209-
result = subKey.GetValue(valueName);
210-
}
211-
212-
// We've found a value, so stop looking
213-
if (result != null)
214-
{
215-
break;
209+
// If we managed to retrieve the subkey, then move onto locating the value
210+
if (subKey != null)
211+
{
212+
result = subKey.GetValue(valueName);
213+
}
214+
215+
// We've found a value, so stop looking
216+
if (result != null)
217+
{
218+
break;
219+
}
216220
}
217221
}
218222
}
219223
}
224+
finally
225+
{
226+
key?.Dispose();
227+
}
220228
}
221229
}
222230

src/Shared/NodeEndpointOutOfProcBase.cs

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -481,15 +481,10 @@ private void PacketPumpProc()
481481
}
482482
}
483483

484-
using (var localReadPipe = new BufferedReadStream(_pipeServer))
485-
{
486-
RunReadLoop(
487-
localReadPipe,
488-
_pipeServer,
489-
localPacketQueue,
490-
localPacketAvailable,
491-
localTerminatePacketPump);
492-
}
484+
RunReadLoop(
485+
new BufferedReadStream(_pipeServer),
486+
_pipeServer,
487+
localPacketQueue, localPacketAvailable, localTerminatePacketPump);
493488

494489
CommunicationsUtilities.Trace("Ending read loop");
495490

@@ -513,12 +508,8 @@ private void PacketPumpProc()
513508
}
514509
}
515510

516-
private void RunReadLoop(
517-
Stream localReadPipe,
518-
Stream localWritePipe,
519-
ConcurrentQueue<INodePacket> localPacketQueue,
520-
AutoResetEvent localPacketAvailable,
521-
AutoResetEvent localTerminatePacketPump)
511+
private void RunReadLoop(Stream localReadPipe, Stream localWritePipe,
512+
ConcurrentQueue<INodePacket> localPacketQueue, AutoResetEvent localPacketAvailable, AutoResetEvent localTerminatePacketPump)
522513
{
523514
// Ordering of the wait handles is important. The first signalled wait handle in the array
524515
// will be returned by WaitAny if multiple wait handles are signalled. We prefer to have the

src/Tasks/AppConfig/AppConfig.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,10 @@ internal void Load(string appConfigFilePath)
3434
// Need a filestream as the XmlReader doesn't support nonstandard unicode characters in path.
3535
// No need to dispose - as 'CloseInput' was passed to XmlReaderSettings
3636
FileStream fs = File.OpenRead(appConfigFilePath);
37-
reader = XmlReader.Create(fs, readerSettings);
38-
Read(reader);
37+
using (reader = XmlReader.Create(fs, readerSettings))
38+
{
39+
Read(reader);
40+
}
3941
}
4042
catch (XmlException e)
4143
{

src/Tasks/BootstrapperUtil/BootstrapperBuilder.cs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,8 @@ public BuildResults Build(BuildSettings settings)
225225
var fi = new FileInfo(de.Value);
226226
using (FileStream fs = fi.OpenRead())
227227
{
228-
data = new StreamReader(fs).ReadToEnd();
228+
using var sr = new StreamReader(fs);
229+
data = sr.ReadToEnd();
229230
}
230231

231232
resourceUpdater.AddStringResource(44, de.Key, data);
@@ -835,7 +836,7 @@ private XmlDocument LoadAndValidateXmlDocument(string filePath, bool validateFil
835836
if (validate)
836837
{
837838
#pragma warning disable 618 // Using XmlValidatingReader. TODO: We need to switch to using XmlReader.Create() with validation.
838-
var validatingReader = new XmlValidatingReader(xmlReader);
839+
using var validatingReader = new XmlValidatingReader(xmlReader);
839840
#pragma warning restore 618
840841
var xrSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, CloseInput = true };
841842
FileStream fs = File.OpenRead(schemaPath);
@@ -1657,7 +1658,7 @@ private static string GetFileHash(string filePath)
16571658
// pre-signed anwyay; this is a fallback in case we ever encounter a bootstrapper that is
16581659
// not signed.
16591660
#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter
1660-
System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create(
1661+
using System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create(
16611662
#if FEATURE_CRYPTOGRAPHIC_FACTORY_ALGORITHM_NAMES
16621663
"System.Security.Cryptography.SHA256CryptoServiceProvider"
16631664
#endif
@@ -2033,7 +2034,8 @@ private static void DumpXmlToFile(XmlNode node, string fileName)
20332034
{
20342035
xmlwriter.Formatting = Formatting.Indented;
20352036
xmlwriter.Indentation = 4;
2036-
xmlwriter.WriteNode(new XmlNodeReader(node), true);
2037+
using var xmlReader = new XmlNodeReader(node);
2038+
xmlwriter.WriteNode(xmlReader, true);
20372039
}
20382040
}
20392041
catch (IOException)
@@ -2194,7 +2196,7 @@ private static string GetPublicKeyOfFile(string fileSource)
21942196
{
21952197
try
21962198
{
2197-
var cert = new X509Certificate(fileSource);
2199+
using var cert = new X509Certificate(fileSource);
21982200
string publicKey = cert.GetPublicKeyString();
21992201
return publicKey;
22002202
}

src/Tasks/CodeTaskFactory.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -738,7 +738,7 @@ private Assembly CompileInMemoryAssembly()
738738

739739
// Horrible code dom / compilation declarations
740740
var codeBuilder = new StringBuilder();
741-
var writer = new StringWriter(codeBuilder, CultureInfo.CurrentCulture);
741+
using var writer = new StringWriter(codeBuilder, CultureInfo.CurrentCulture);
742742
var codeGeneratorOptions = new CodeGeneratorOptions
743743
{
744744
BlankLinesBetweenMembers = true,

src/Tasks/DownloadFile.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,8 @@ private async Task<bool> ExecuteAsync()
146146
private async Task DownloadAsync(Uri uri, CancellationToken cancellationToken)
147147
{
148148
// The main reason to use HttpClient vs WebClient is because we can pass a message handler for unit tests to mock
149-
using (var client = new HttpClient(HttpMessageHandler ?? new HttpClientHandler(), disposeHandler: true) { Timeout = TimeSpan.FromMilliseconds(Timeout) })
149+
using var httpHandler = new HttpClientHandler();
150+
using (var client = new HttpClient(HttpMessageHandler ?? httpHandler, disposeHandler: true) { Timeout = TimeSpan.FromMilliseconds(Timeout) })
150151
{
151152
// Only get the response without downloading the file so we can determine if the file is already up-to-date
152153
using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false))

src/Tasks/GenerateResource.cs

Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -975,7 +975,7 @@ private bool IsDangerous(String filename)
975975
dangerous = false;
976976

977977
FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
978-
XmlTextReader reader = new XmlTextReader(stream);
978+
using XmlTextReader reader = new XmlTextReader(stream);
979979
reader.DtdProcessing = DtdProcessing.Ignore;
980980
reader.XmlResolver = null;
981981
try
@@ -1622,14 +1622,13 @@ private bool NeedToRebuildSourceFile(string sourceFilePath, DateTime sourceTime,
16221622
private void GetStronglyTypedResourceToProcess(ref List<ITaskItem> inputsToProcess, ref List<ITaskItem> outputsToProcess)
16231623
{
16241624
bool needToRebuildSTR = false;
1625+
CodeDomProvider provider = null;
16251626

16261627
// The resource file isn't out of date. So check whether the STR class file is.
16271628
try
16281629
{
16291630
if (StronglyTypedFileName == null)
16301631
{
1631-
CodeDomProvider provider = null;
1632-
16331632
if (ProcessResourceFiles.TryCreateCodeDomProvider(Log, StronglyTypedLanguage, out provider))
16341633
{
16351634
StronglyTypedFileName = ProcessResourceFiles.GenerateDefaultStronglyTypedFilename(provider, OutputResources[0].ItemSpec);
@@ -1645,6 +1644,10 @@ private void GetStronglyTypedResourceToProcess(ref List<ITaskItem> inputsToProce
16451644
_stronglyTypedResourceSuccessfullyCreated = false;
16461645
return;
16471646
}
1647+
finally
1648+
{
1649+
provider?.Dispose();
1650+
}
16481651

16491652
// Now we have the filename, check if it's up to date
16501653
DateTime sourceTime = NativeMethodsShared.GetLastWriteFileUtcTime(Sources[0].ItemSpec);
@@ -2153,11 +2156,20 @@ private void RecordFilesWritten()
21532156
{
21542157
if (StronglyTypedFileName == null)
21552158
{
2156-
CodeDomProvider provider;
2157-
if (ProcessResourceFiles.TryCreateCodeDomProvider(Log, StronglyTypedLanguage, out provider))
2159+
CodeDomProvider provider = null;
2160+
try
2161+
{
2162+
if (ProcessResourceFiles.TryCreateCodeDomProvider(Log, StronglyTypedLanguage, out provider))
2163+
{
2164+
StronglyTypedFileName = ProcessResourceFiles.GenerateDefaultStronglyTypedFilename(
2165+
provider, OutputResources[0].ItemSpec);
2166+
2167+
provider.Dispose();
2168+
}
2169+
}
2170+
finally
21582171
{
2159-
StronglyTypedFileName = ProcessResourceFiles.GenerateDefaultStronglyTypedFilename(
2160-
provider, OutputResources[0].ItemSpec);
2172+
provider?.Dispose();
21612173
}
21622174
}
21632175

@@ -3412,11 +3424,18 @@ private bool HaveSystemResourcesExtensionsReference
34123424
/// <param name="sourceFile">The generated strongly typed filename</param>
34133425
private void CreateStronglyTypedResources(ReaderInfo reader, String outFile, String inputFileName, out String sourceFile)
34143426
{
3415-
CodeDomProvider provider;
3416-
if (!TryCreateCodeDomProvider(_logger, _stronglyTypedLanguage, out provider))
3427+
CodeDomProvider provider = null;
3428+
try
34173429
{
3418-
sourceFile = null;
3419-
return;
3430+
if (!TryCreateCodeDomProvider(_logger, _stronglyTypedLanguage, out provider))
3431+
{
3432+
sourceFile = null;
3433+
return;
3434+
}
3435+
}
3436+
finally
3437+
{
3438+
provider?.Dispose();
34203439
}
34213440

34223441
// Default the class name if we need to
@@ -3542,15 +3561,16 @@ private void ReadResources(ReaderInfo readerInfo, IResourceReader reader, String
35423561
#endif // FEATURE_RESXREADER_LIVEDESERIALIZATION
35433562

35443563
/// <summary>
3545-
/// Read resources from a text format file
3564+
/// Read resources from a text format file.
35463565
/// </summary>
3547-
/// <param name="reader">Reader info</param>
3548-
/// <param name="fileName">Input resources filename</param>
3566+
/// <param name="reader">Reader info.</param>
3567+
/// <param name="fileName">Input resources filename.</param>
35493568
private void ReadTextResources(ReaderInfo reader, String fileName)
35503569
{
35513570
// Check for byte order marks in the beginning of the input file, but
35523571
// default to UTF-8.
3553-
using (LineNumberStreamReader sr = new LineNumberStreamReader(fileName, new UTF8Encoding(true), true))
3572+
using var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
3573+
using (LineNumberStreamReader sr = new LineNumberStreamReader(fs, new UTF8Encoding(true), true))
35543574
{
35553575
StringBuilder name = new StringBuilder(255);
35563576
StringBuilder value = new StringBuilder(2048);
@@ -3876,8 +3896,8 @@ internal sealed class LineNumberStreamReader : StreamReader
38763896
private int _lineNumber;
38773897
private int _col;
38783898

3879-
internal LineNumberStreamReader(String fileName, Encoding encoding, bool detectEncoding)
3880-
: base(File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read), encoding, detectEncoding)
3899+
internal LineNumberStreamReader(Stream fileStream, Encoding encoding, bool detectEncoding)
3900+
: base(fileStream, encoding, detectEncoding)
38813901
{
38823902
_lineNumber = 1;
38833903
_col = 0;

src/Tasks/GetAssembliesMetadata.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ public override bool Execute()
5050
// During DTB the referenced project may not has been built yet, so we need to check if the assembly already exists.
5151
if (File.Exists(assemblyPath))
5252
{
53-
AssemblyInformation assemblyInformation = new(assemblyPath);
53+
using AssemblyInformation assemblyInformation = new(assemblyPath);
5454
AssemblyAttributes attributes = assemblyInformation.GetAssemblyMetadata();
5555

5656
if (attributes != null)

src/Tasks/GetInstalledSDKLocations.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ public override bool Execute()
194194
object staticCacheDisposer = buildEngine4.GetRegisteredTaskObject(StaticSDKCacheKey, RegisteredTaskObjectLifetime.Build);
195195
if (staticCacheDisposer == null)
196196
{
197-
BuildCacheDisposeWrapper staticDisposer = new BuildCacheDisposeWrapper(ToolLocationHelper.ClearSDKStaticCache);
197+
using BuildCacheDisposeWrapper staticDisposer = new BuildCacheDisposeWrapper(ToolLocationHelper.ClearSDKStaticCache);
198198
buildEngine4.RegisterTaskObject(StaticSDKCacheKey, staticDisposer, RegisteredTaskObjectLifetime.Build, allowEarlyCollection: false);
199199
}
200200
}

0 commit comments

Comments
 (0)