房產 | 價值觀 |
---|---|
規則識別碼 | CA2025 |
職稱 | 請勿將 『IDisposable』 實例傳遞至未喚醒的工作 |
類別 | 可靠性 |
修正是破壞性或非破壞性 | 不分割 |
預設在 .NET 10 中啟用 |
否 |
原因
IDisposable
實例會傳遞至未喚醒的工作,並可能在工作使用 實例完成之前處置。
規則描述
使用 IDisposable
實例的未喚醒工作可能會在處置實例之後很久就使用這些實例。 在處置實例之前,請確定使用這些實例的工作已完成。
範例
下列代碼段(及其 Visual Basic 對等專案)違反 CA2025:
public Task DoSomethingAsync()
{
// Using statements and using blocks can both be violations.
using (var disposable = new DisposableThing())
{
return DoSomethingInternalAsync(disposable);
}
}
public async Task DoThingsAsync()
{
var disposable = new DisposableThing();
var task = DoSomethingInternalAsync(disposable);
// More code here.
dispose.Dispose();
// It's a violation if arguments are disposed before the task is awaited.
await task.ConfigureAwait(false);
}
隱藏警告的時機
如果您知道工作在處置之前使用 IDisposable
實例完成,請隱藏這些警告。
隱藏警告
如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable CA2025
// The code that's violating the rule is on this line.
#pragma warning restore CA2025
若要停用檔案、資料夾或項目的規則,請在none
中將其嚴重性設為。
[*.{cs,vb}]
dotnet_diagnostic.CA2025.severity = none
如需詳細資訊,請參閱 如何隱藏程式代碼分析警告。