| Property | Value |
|---|---|
| 規則識別碼 | IDE0390,IDE0391 |
| Title | 讓方法同步 |
| Category | Style |
| 子類別 | 不必要的程式碼規則 (修飾符偏好設定) |
| 適用語言 | C# |
| 選項 | 沒有 |
Overview
這些規則會標記 async 不包含任何 await 表達式的方法。 為了獲得更好的效能,請移除 async 修飾詞並調整傳回類型,因為從未 await 任何內容的 async 方法會同步執行,但仍須承受 async 狀態機的額外負擔。
這兩條規則針對不同的情境:
-
IDE0390:回報
async非介面實作或覆寫的方法、本地函式和 lambda 表達式。 - IDE0391:報告實作介面成員或覆寫基底類別方法的方法。
為避免破壞呼叫者透過介面 await 該方法的能力,將此修正套用至介面實作或覆寫時務必謹慎。 移除 async 在這些情況下可能會帶來不同的行為影響。
Example
// Code with violations.
// IDE0390: Regular method with no 'await'.
public async Task<int> GetValueAsync()
{
return 42;
}
// IDE0391: Override method with no 'await'.
public override async Task<string> GetNameAsync()
{
return "example";
}
// Fixed code.
// Remove 'async' and return the value directly.
public Task<int> GetValueAsync()
{
return Task.FromResult(42);
}
// Remove 'async' and return the value directly.
public override Task<string> GetNameAsync()
{
return Task.FromResult("example");
}
隱藏警告
如果您想要只隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable IDE0390
// The code that's violating the rule is on this line.
#pragma warning restore IDE0390
若要停用檔案、資料夾或項目的規則,請在none中將其嚴重性設定為。
[*.cs]
dotnet_diagnostic.IDE0390.severity = none
dotnet_diagnostic.IDE0391.severity = none
若要停用所有程式碼樣式規則,請將類別 Style 的嚴重性設定為 組態檔中的 none。
[*.cs]
dotnet_analyzer_diagnostic.category-Style.severity = none
如需詳細資訊,請參閱 如何隱藏程式碼分析警告。