Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
dispose part 3
  • Loading branch information
YuliiaKovalova committed Apr 11, 2024
commit 6b56301bafbabe9082d9aaac311b8960895f46aa
2 changes: 1 addition & 1 deletion src/Build/BackEnd/BuildManager/LegacyThreadingData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ internal int MainThreadSubmissionId
/// Given a submission ID, assign it "start" and "finish" events to track its use of
/// the legacy thread.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA2000:Dispose objects before losing scope", Justification = "The events are disposed in UnregisterSubmissionForLegacyThread")]
[SuppressMessage("Microsoft.Dispose", "CA2000:Dispose objects before losing scope", Justification = "The events are disposed in UnregisterSubmissionForLegacyThread")]
internal void RegisterSubmissionForLegacyThread(int submissionId)
{
lock (_legacyThreadingEventsLock)
Expand Down
32 changes: 20 additions & 12 deletions src/Deprecated/Engine/Engine/IntrinsicFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,26 +197,34 @@ internal static object GetRegistryValueFromView(string keyName, string valueName
// of that error.
RegistryView view = (RegistryView)Enum.Parse(typeof(RegistryView), viewAsString, true);

using (RegistryKey key = GetBaseKeyFromKeyName(keyName, view, out subKeyName))
RegistryKey key = null;
try
{
if (key != null)
using (key = GetBaseKeyFromKeyName(keyName, view, out subKeyName))
{
using (RegistryKey subKey = key.OpenSubKey(subKeyName, false))
if (key != null)
{
// If we managed to retrieve the subkey, then move onto locating the value
if (subKey != null)
using (RegistryKey subKey = key.OpenSubKey(subKeyName, false))
{
result = subKey.GetValue(valueName);
}

// We've found a value, so stop looking
if (result != null)
{
break;
// If we managed to retrieve the subkey, then move onto locating the value
if (subKey != null)
{
result = subKey.GetValue(valueName);
}

// We've found a value, so stop looking
if (result != null)
{
break;
}
}
}
}
}
finally
{
key?.Dispose();
Comment thread
YuliiaKovalova marked this conversation as resolved.
Outdated
}
}
}

Expand Down
21 changes: 6 additions & 15 deletions src/Shared/NodeEndpointOutOfProcBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -481,15 +481,10 @@ private void PacketPumpProc()
}
}

using (var localReadPipe = new BufferedReadStream(_pipeServer))
{
RunReadLoop(
localReadPipe,
_pipeServer,
localPacketQueue,
localPacketAvailable,
localTerminatePacketPump);
}
RunReadLoop(
new BufferedReadStream(_pipeServer),
_pipeServer,
localPacketQueue, localPacketAvailable, localTerminatePacketPump);

CommunicationsUtilities.Trace("Ending read loop");

Expand All @@ -513,12 +508,8 @@ private void PacketPumpProc()
}
}

private void RunReadLoop(
Stream localReadPipe,
Stream localWritePipe,
ConcurrentQueue<INodePacket> localPacketQueue,
AutoResetEvent localPacketAvailable,
AutoResetEvent localTerminatePacketPump)
private void RunReadLoop(Stream localReadPipe, Stream localWritePipe,
ConcurrentQueue<INodePacket> localPacketQueue, AutoResetEvent localPacketAvailable, AutoResetEvent localTerminatePacketPump)
{
// Ordering of the wait handles is important. The first signalled wait handle in the array
// will be returned by WaitAny if multiple wait handles are signalled. We prefer to have the
Expand Down
6 changes: 4 additions & 2 deletions src/Tasks/AppConfig/AppConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,10 @@ internal void Load(string appConfigFilePath)
// Need a filestream as the XmlReader doesn't support nonstandard unicode characters in path.
// No need to dispose - as 'CloseInput' was passed to XmlReaderSettings
FileStream fs = File.OpenRead(appConfigFilePath);
reader = XmlReader.Create(fs, readerSettings);
Read(reader);
using (reader = XmlReader.Create(fs, readerSettings))
Comment thread
YuliiaKovalova marked this conversation as resolved.
Outdated
{
Read(reader);
}
}
catch (XmlException e)
{
Expand Down
12 changes: 7 additions & 5 deletions src/Tasks/BootstrapperUtil/BootstrapperBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,8 @@ public BuildResults Build(BuildSettings settings)
var fi = new FileInfo(de.Value);
using (FileStream fs = fi.OpenRead())
{
data = new StreamReader(fs).ReadToEnd();
using var sr = new StreamReader(fs);
data = sr.ReadToEnd();
}

resourceUpdater.AddStringResource(44, de.Key, data);
Expand Down Expand Up @@ -835,7 +836,7 @@ private XmlDocument LoadAndValidateXmlDocument(string filePath, bool validateFil
if (validate)
{
#pragma warning disable 618 // Using XmlValidatingReader. TODO: We need to switch to using XmlReader.Create() with validation.
var validatingReader = new XmlValidatingReader(xmlReader);
using var validatingReader = new XmlValidatingReader(xmlReader);
#pragma warning restore 618
var xrSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, CloseInput = true };
FileStream fs = File.OpenRead(schemaPath);
Expand Down Expand Up @@ -1657,7 +1658,7 @@ private static string GetFileHash(string filePath)
// pre-signed anwyay; this is a fallback in case we ever encounter a bootstrapper that is
// not signed.
#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter
System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create(
using System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create(
#if FEATURE_CRYPTOGRAPHIC_FACTORY_ALGORITHM_NAMES
"System.Security.Cryptography.SHA256CryptoServiceProvider"
#endif
Expand Down Expand Up @@ -2033,7 +2034,8 @@ private static void DumpXmlToFile(XmlNode node, string fileName)
{
xmlwriter.Formatting = Formatting.Indented;
xmlwriter.Indentation = 4;
xmlwriter.WriteNode(new XmlNodeReader(node), true);
using var xmlReader = new XmlNodeReader(node);
xmlwriter.WriteNode(xmlReader, true);
}
}
catch (IOException)
Expand Down Expand Up @@ -2194,7 +2196,7 @@ private static string GetPublicKeyOfFile(string fileSource)
{
try
{
var cert = new X509Certificate(fileSource);
using var cert = new X509Certificate(fileSource);
string publicKey = cert.GetPublicKeyString();
return publicKey;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Tasks/CodeTaskFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,7 @@ private Assembly CompileInMemoryAssembly()

// Horrible code dom / compilation declarations
var codeBuilder = new StringBuilder();
var writer = new StringWriter(codeBuilder, CultureInfo.CurrentCulture);
using var writer = new StringWriter(codeBuilder, CultureInfo.CurrentCulture);
var codeGeneratorOptions = new CodeGeneratorOptions
{
BlankLinesBetweenMembers = true,
Expand Down
3 changes: 2 additions & 1 deletion src/Tasks/DownloadFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,8 @@ private async Task<bool> ExecuteAsync()
private async Task DownloadAsync(Uri uri, CancellationToken cancellationToken)
{
// The main reason to use HttpClient vs WebClient is because we can pass a message handler for unit tests to mock
using (var client = new HttpClient(HttpMessageHandler ?? new HttpClientHandler(), disposeHandler: true) { Timeout = TimeSpan.FromMilliseconds(Timeout) })
using var httpHandler = new HttpClientHandler();
Comment thread
YuliiaKovalova marked this conversation as resolved.
Outdated
using (var client = new HttpClient(HttpMessageHandler ?? httpHandler, disposeHandler: true) { Timeout = TimeSpan.FromMilliseconds(Timeout) })
{
// Only get the response without downloading the file so we can determine if the file is already up-to-date
using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false))
Expand Down
54 changes: 37 additions & 17 deletions src/Tasks/GenerateResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -975,7 +975,7 @@ private bool IsDangerous(String filename)
dangerous = false;

FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
Comment thread
YuliiaKovalova marked this conversation as resolved.
Outdated
XmlTextReader reader = new XmlTextReader(stream);
using XmlTextReader reader = new XmlTextReader(stream);
reader.DtdProcessing = DtdProcessing.Ignore;
reader.XmlResolver = null;
try
Expand Down Expand Up @@ -1622,14 +1622,13 @@ private bool NeedToRebuildSourceFile(string sourceFilePath, DateTime sourceTime,
private void GetStronglyTypedResourceToProcess(ref List<ITaskItem> inputsToProcess, ref List<ITaskItem> outputsToProcess)
{
bool needToRebuildSTR = false;
CodeDomProvider provider = null;

// The resource file isn't out of date. So check whether the STR class file is.
try
{
if (StronglyTypedFileName == null)
{
CodeDomProvider provider = null;

if (ProcessResourceFiles.TryCreateCodeDomProvider(Log, StronglyTypedLanguage, out provider))
{
StronglyTypedFileName = ProcessResourceFiles.GenerateDefaultStronglyTypedFilename(provider, OutputResources[0].ItemSpec);
Expand All @@ -1645,6 +1644,10 @@ private void GetStronglyTypedResourceToProcess(ref List<ITaskItem> inputsToProce
_stronglyTypedResourceSuccessfullyCreated = false;
return;
}
finally
{
provider?.Dispose();
}

// Now we have the filename, check if it's up to date
DateTime sourceTime = NativeMethodsShared.GetLastWriteFileUtcTime(Sources[0].ItemSpec);
Expand Down Expand Up @@ -2153,11 +2156,20 @@ private void RecordFilesWritten()
{
if (StronglyTypedFileName == null)
{
CodeDomProvider provider;
if (ProcessResourceFiles.TryCreateCodeDomProvider(Log, StronglyTypedLanguage, out provider))
CodeDomProvider provider = null;
try
{
if (ProcessResourceFiles.TryCreateCodeDomProvider(Log, StronglyTypedLanguage, out provider))
{
StronglyTypedFileName = ProcessResourceFiles.GenerateDefaultStronglyTypedFilename(
provider, OutputResources[0].ItemSpec);

provider.Dispose();
Comment thread
YuliiaKovalova marked this conversation as resolved.
Outdated
}
}
finally
{
StronglyTypedFileName = ProcessResourceFiles.GenerateDefaultStronglyTypedFilename(
provider, OutputResources[0].ItemSpec);
provider?.Dispose();
}
}

Expand Down Expand Up @@ -3412,11 +3424,18 @@ private bool HaveSystemResourcesExtensionsReference
/// <param name="sourceFile">The generated strongly typed filename</param>
private void CreateStronglyTypedResources(ReaderInfo reader, String outFile, String inputFileName, out String sourceFile)
{
CodeDomProvider provider;
if (!TryCreateCodeDomProvider(_logger, _stronglyTypedLanguage, out provider))
CodeDomProvider provider = null;
try
{
sourceFile = null;
return;
if (!TryCreateCodeDomProvider(_logger, _stronglyTypedLanguage, out provider))
{
sourceFile = null;
return;
}
}
finally
{
provider?.Dispose();
}
Comment thread
YuliiaKovalova marked this conversation as resolved.
Outdated

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

/// <summary>
/// Read resources from a text format file
/// Read resources from a text format file.
/// </summary>
/// <param name="reader">Reader info</param>
/// <param name="fileName">Input resources filename</param>
/// <param name="reader">Reader info.</param>
/// <param name="fileName">Input resources filename.</param>
private void ReadTextResources(ReaderInfo reader, String fileName)
{
// Check for byte order marks in the beginning of the input file, but
// default to UTF-8.
using (LineNumberStreamReader sr = new LineNumberStreamReader(fileName, new UTF8Encoding(true), true))
using var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
using (LineNumberStreamReader sr = new LineNumberStreamReader(fs, new UTF8Encoding(true), true))
{
StringBuilder name = new StringBuilder(255);
StringBuilder value = new StringBuilder(2048);
Expand Down Expand Up @@ -3876,8 +3896,8 @@ internal sealed class LineNumberStreamReader : StreamReader
private int _lineNumber;
private int _col;

internal LineNumberStreamReader(String fileName, Encoding encoding, bool detectEncoding)
: base(File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read), encoding, detectEncoding)
internal LineNumberStreamReader(Stream fileStream, Encoding encoding, bool detectEncoding)
: base(fileStream, encoding, detectEncoding)
{
_lineNumber = 1;
_col = 0;
Expand Down
2 changes: 1 addition & 1 deletion src/Tasks/GetAssembliesMetadata.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public override bool Execute()
// During DTB the referenced project may not has been built yet, so we need to check if the assembly already exists.
if (File.Exists(assemblyPath))
{
AssemblyInformation assemblyInformation = new(assemblyPath);
using AssemblyInformation assemblyInformation = new(assemblyPath);
AssemblyAttributes attributes = assemblyInformation.GetAssemblyMetadata();

if (attributes != null)
Expand Down
2 changes: 1 addition & 1 deletion src/Tasks/GetInstalledSDKLocations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ public override bool Execute()
object staticCacheDisposer = buildEngine4.GetRegisteredTaskObject(StaticSDKCacheKey, RegisteredTaskObjectLifetime.Build);
if (staticCacheDisposer == null)
{
BuildCacheDisposeWrapper staticDisposer = new BuildCacheDisposeWrapper(ToolLocationHelper.ClearSDKStaticCache);
using BuildCacheDisposeWrapper staticDisposer = new BuildCacheDisposeWrapper(ToolLocationHelper.ClearSDKStaticCache);
Comment thread
YuliiaKovalova marked this conversation as resolved.
Outdated
buildEngine4.RegisterTaskObject(StaticSDKCacheKey, staticDisposer, RegisteredTaskObjectLifetime.Build, allowEarlyCollection: false);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Tasks/ManifestUtil/ManifestFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ public static Stream Format(Stream input)
{
int t1 = Environment.TickCount;

var r = new XmlTextReader(input)
using var r = new XmlTextReader(input)
{
DtdProcessing = DtdProcessing.Ignore,
WhitespaceHandling = WhitespaceHandling.None
};
XmlNamespaceManager nsmgr = XmlNamespaces.GetNamespaceManager(r.NameTable);

var m = new MemoryStream();
var w = new XmlTextWriter(m, Encoding.UTF8)
using var w = new XmlTextWriter(m, Encoding.UTF8)
{
Formatting = Formatting.Indented,
Indentation = 2
Expand Down
2 changes: 1 addition & 1 deletion src/Tasks/ManifestUtil/ManifestReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ public static Manifest ReadManifest(string manifestType, Stream input, bool pres
private static Manifest Deserialize(Stream s)
{
s.Position = 0;
var r = new XmlTextReader(s) { DtdProcessing = DtdProcessing.Ignore };
using var r = new XmlTextReader(s) { DtdProcessing = DtdProcessing.Ignore };

do
{
Expand Down
2 changes: 1 addition & 1 deletion src/Tasks/ManifestUtil/ManifestWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ private static Stream Serialize(Manifest manifest)
manifest.OnBeforeSave();
var m = new MemoryStream();
var s = new XmlSerializer(manifest.GetType());
var w = new StreamWriter(m);
using var w = new StreamWriter(m);
Comment thread
YuliiaKovalova marked this conversation as resolved.
Outdated

int t1 = Environment.TickCount;
s.Serialize(w, manifest);
Expand Down
6 changes: 3 additions & 3 deletions src/Tasks/ManifestUtil/SecurityUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ private static XmlElement GetXmlElement(string targetZone, FrameworkName fn)
{
try
{
var sr = new StreamReader(fs);
using var sr = new StreamReader(fs);
Comment thread
YuliiaKovalova marked this conversation as resolved.
Outdated
string data = sr.ReadToEnd();
if (!string.IsNullOrEmpty(data))
{
Expand Down Expand Up @@ -610,7 +610,7 @@ public static void SignFile(string certThumbprint,
[SupportedOSPlatform("windows")]
public static void SignFile(string certPath, SecureString certPassword, Uri timestampUrl, string path)
{
X509Certificate2 cert = new X509Certificate2(certPath, certPassword, X509KeyStorageFlags.PersistKeySet);
using X509Certificate2 cert = new X509Certificate2(certPath, certPassword, X509KeyStorageFlags.PersistKeySet);
SignFile(cert, timestampUrl, path);
}

Expand Down Expand Up @@ -705,7 +705,7 @@ private static void SignFileInternal(X509Certificate2 cert,
CmiManifestSigner2 signer;
if (useSha256 && rsa is RSACryptoServiceProvider rsacsp)
{
RSACryptoServiceProvider csp = SignedCmiManifest2.GetFixedRSACryptoServiceProvider(rsacsp, useSha256);
using RSACryptoServiceProvider csp = SignedCmiManifest2.GetFixedRSACryptoServiceProvider(rsacsp, useSha256);
signer = new CmiManifestSigner2(csp, cert, useSha256);
Comment thread
YuliiaKovalova marked this conversation as resolved.
Outdated
}
else
Expand Down
3 changes: 2 additions & 1 deletion src/Tasks/ManifestUtil/TrustInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,8 @@ public override string ToString()
var m = new MemoryStream();
Write(m);
m.Position = 0;
var r = new StreamReader(m);
using var r = new StreamReader(m);

return r.ReadToEnd();
}

Expand Down
Loading