I have some integration tests using xUnit that need to tear down some resources created during the test. To do that, I have implemented IDisposable
in the class containing the tests.
The problem is I need to delete resources created during the test using a client that has only an asynchronous interface. But, the Dispose
method is synchronous.
I could use .Result
or .Wait()
to wait for the completion of the asynchronous call, but that may create deadlocks (the issue is well-documented here).
Given I cannot use .Result
or .Wait()
, what is the proper (and safe) way to call an asynchronous method in a Dispose
method?
UPDATE: adding a (simplified) example to show the problem.
[Collection("IntegrationTests")]
public class SomeIntegrationTests : IDisposable {
private readonly IClient _client; // SDK client for external API
public SomeIntegrationTests() {
// initialize client
}
[Fact]
public async Task Test1() {
await _client
.ExecuteAsync(/* a request that creates resources */);
// some assertions
}
public void Dispose() {
_client
.ExecuteAsync(/* a request to delete previously created resources */)
.Wait(); // this may create a deadlock
}
}