Roslyn analyzers for detecting memory leaks and performance issues in .NET code. Shows warnings directly in Visual Studio.
$ dotnet add package MemoryLeakDetector.AnalyzersRoslyn analyzers for detecting memory leaks and performance issues in .NET code.
dotnet add package MemoryLeakDetector.Analyzers
| Rule | Description |
|---|---|
| MLD001 | HttpClient created per request (causes socket exhaustion) |
| MLD002 | Class has disposable field but doesn't implement IDisposable |
| MLD003 | Async void method (exceptions cannot be caught) |
| MLD004 | Timer field without IDisposable implementation |
| Rule | Description |
|---|---|
| PERF001 | String concatenation in loop (use StringBuilder) |
| PERF002 | ContainsKey + indexer (use TryGetValue) |
| PERF003 | ToLower/ToUpper for comparison (use StringComparison) |
// ❌ Bad - creates socket exhaustion
public async Task<string> GetData()
{
var client = new HttpClient(); // Warning: MLD001
return await client.GetStringAsync(url);
}
// ✅ Good - reuse HttpClient
private static readonly HttpClient _client = new HttpClient();
public async Task<string> GetData()
{
return await _client.GetStringAsync(url);
}
// ❌ Bad - FileStream not disposed
public class MyService
{
private FileStream _file; // Warning: MLD002
}
// ✅ Good - implements IDisposable
public class MyService : IDisposable
{
private FileStream _file;
public void Dispose() => _file?.Dispose();
}
// ❌ Bad - creates many temporary strings
var result = "";
foreach (var item in items)
{
result += item; // Info: PERF001
}
// ✅ Good - use StringBuilder
var sb = new StringBuilder();
foreach (var item in items)
{
sb.Append(item);
}
You can configure rule severity in .editorconfig:
# Disable a rule
dotnet_diagnostic.MLD001.severity = none
# Make a rule an error (fails build)
dotnet_diagnostic.MLD002.severity = error
# Change performance rules to warnings
dotnet_diagnostic.PERF001.severity = warningMIT