Constructors cannot be asynchronous. Therefore, developers tend to call asynchronous APIs from the constructor blockingly, either using Wait()
or Result
.
class FileResource {
public string Content { get; }
public FileResource(string filePath) {
Content = File.ReadAllTextAsync(filePath).Result;
}
}
Invoking async methods to await their completion blockingly is generally discouraged, as stated by PH_P005.
Refactor the constructor to an async
factory method that the caller can await. Alternatively, the invocation of the blocking counterpart might be an acceptable solution here.
// Solution #1 - Refactor to factory method (recommended)
class FileResource {
public string Content { get; }
private FileResource(string content) {
Content = content;
}
public static async Task<FileResource> CreateAsync(string filePath) {
return new FileResource(
await File.ReadAllTextAsync(filePath)
);
}
}
// Solution #2 - Call the synchronous API
class FileResource {
public string Content { get; }
public FileResource(string filePath) {
Content = File.ReadAllText(filePath);
}
}