Skip to content

Latest commit

 

History

History
44 lines (34 loc) · 1.28 KB

PH_B016.md

File metadata and controls

44 lines (34 loc) · 1.28 KB

PH_B016 - Exception handling on unawaited Task

Problem

A method invokes an async method without awaiting the task but returns the task immediatly as a shortcut. Since the invoked async method may throw an exception, e.g. an IOException as the example below illustrates, an exception handler is used. However, because the invoked method is not awaited, the exception handler will become ineffective since the actual exception is encapsulated in the returned task. Therefore, the exception bubbles up to the method that awaits the returned task.

using System.Net;
using System.Threading.Tasks;

class Test {
  private readonly WebClient = new WebClient();

  public Task<string> GetEventsAsync() {
    try {
      return client.DownloadStringTaskAsync("https://api.github.com/events");
    } catch(IOException) {
      // Never triggered
    }
  }
}

Solution

Make the enclosing method async and await the returned task.

using System.Net;
using System.Threading.Tasks;

class Test {
  private readonly WebClient = new WebClient();

  public async Task<string> GetEventsAsync() {
    try {
      return await client.DownloadStringTaskAsync("https://api.github.com/events");
    } catch(IOException) {
      // Now triggered since the download task is awaited
    }
  }
}