Captured variable is disposed in outer scope

I have the following piece of sample code to which resharper complains "Captured variable is disposed in outer scope". I do not any issues here as ExecuteAsync which calls the unnamed lambda is awaited so httpClient will not be used outside the scope. Is this a false positive?



  private static async Task MyTestFunction(IHttpClientFactory httpClientFactory) {

            string baseUrl = "http://localhost:8000";
            using var httpClient = httpClientFactory.CreateClient();
            try {
                await ExecuteAsync(
                    async () => {
                        try {
                            await httpClient.GetAsync(new Uri(baseUrl)).ConfigureAwait(false);
                        } catch (Exception ex) {
                            Console.WriteLine(ex);
                            throw;
                        }
                    }).ConfigureAwait(false);
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                throw;
            }
        }

        private static async Task ExecuteAsync(Func<Task> func) {
            await func().ConfigureAwait(false);
        }
2 comments
Comment actions Permalink

Try adding the InstantHandle attribute to the parameter:
https://www.jetbrains.com/help/resharper/Reference__Code_Annotation_Attributes.html#InstantHandleAttribute

private static async Task ExecuteAsync([InstantHandle(RequireAwait = true)] Func<Task> func)
1
Comment actions Permalink

Hello!

Richard is absolutely right. Please try using InstantHandle attribute. ReSharper doesn't perform interprocedural analysis and doesn't know that lambda is going to be executed immediately. 

0

Please sign in to leave a comment.