Skip to content

Instantly share code, notes, and snippets.

@werwolfby
Created June 23, 2020 23:37
Show Gist options
  • Save werwolfby/db728c98230376ae5b94eaa2dd479acd to your computer and use it in GitHub Desktop.
Save werwolfby/db728c98230376ae5b94eaa2dd479acd to your computer and use it in GitHub Desktop.
WithTimeout extension methods for use in UnitTests
public static class WithTimeoutExtension
{
public static Task WithTimeout(this Task task, int timeout, string actionName = null) => task.WithTimeout(TimeSpan.FromMilliseconds(timeout), actionName);
public static async Task WithTimeout(this Task task, TimeSpan timeout, string actionName = null)
{
var delay = Task.Delay(timeout);
var completedTask = await Task.WhenAny(task, delay);
if (completedTask == task)
{
return;
}
Assert.Fail($"{actionName ?? "Task"} is not completed in {timeout} for {TestContext.CurrentContext.CurrentRepeatCount + 1} try");
}
public static async Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout, string actionName = null)
{
var delay = Task.Delay(timeout);
var completedTask = await Task.WhenAny(task, delay);
if (completedTask == task)
{
return task.GetAwaiter().GetResult();
}
throw new AssertionException($"{actionName ?? "Task"} is not completed in {timeout} for {TestContext.CurrentContext.CurrentRepeatCount + 1} try");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment