dotnet / roslyn-analyzers

MIT License
1.59k stars 465 forks source link

CA2000 doesn't recognize Task completion #2949

Open DRAirey1 opened 5 years ago

DRAirey1 commented 5 years ago

I've got a resource that can only be disposed of once a long running task is completed:

                    StringContent stringContent = new StringContent(JsonConvert.SerializeObject(jObject), Encoding.UTF8, "application/json");
                    Task<HttpResponseMessage> taskResponse = this.httpClient.PutAsync(new Uri($"{api}/{keyProperty}", UriKind.Relative), stringContent);
                    taskResponse.ContinueWith(
                        antecedent =>
                        {
                            // Dispose of the resource.
                            stringContent.Dispose();
                         }

This generates a CA2000 warning even though all paths dispose of the stringContent resource. FxCop apparently wants me to place the dispose on the original thread of this code. This is premature as the HTTP call will fail with an attempt to access a disposed object.

eriove commented 4 years ago

I have the same pattern in my code with the same warning. I suppose it is possible for the task to fail in such a way that the stringContent isn't disposed so the warning is warranted in a way. Annoying to have to suppress it though.

DRAirey1 commented 4 years ago

I suppose it is possible for the task to fail in such a way that the stringContent isn't disposed

This is a hypothetical error. I'm not even sure it's possible to not run the completion task.

But disposing of a resource - that is intended to be used by a task completion thunk - immediately after the task has been started is a real and present error. That's what CA2000 is suggesting currently.