Skip to content

Latest commit

 

History

History
48 lines (35 loc) · 1.22 KB

PH_S035.md

File metadata and controls

48 lines (35 loc) · 1.22 KB

PH_S034 - Blocking Async Method Invocation in Constructor

Problem

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.

Solution

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);
  }
}