Fix possible race between the stats collector and transport controller

Previously, it would be possible for the RTCStatsCollector to start
an async network task to gather stats that would be run after the
PeerConnection was closed when the transport controller was set to
null.

Bug: chromium:829238
Change-Id: I22fb4ce603caf2614814780b95b62127cee28284
Reviewed-on: https://webrtc-review.googlesource.com/72525
Reviewed-by: Henrik Boström <hbos@webrtc.org>
Reviewed-by: Taylor Brandstetter <deadbeef@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#23046}
diff --git a/pc/rtcstats_integrationtest.cc b/pc/rtcstats_integrationtest.cc
index cdc46d7..627a05b 100644
--- a/pc/rtcstats_integrationtest.cc
+++ b/pc/rtcstats_integrationtest.cc
@@ -826,7 +826,20 @@
   caller_ = nullptr;
   // Any pending stats requests should have completed in the act of destroying
   // the peer connection.
-  EXPECT_TRUE(stats_obtainer->report());
+  ASSERT_TRUE(stats_obtainer->report());
+  EXPECT_EQ(stats_obtainer->report()->ToJson(),
+            RTCStatsReportTraceListener::last_trace());
+}
+
+TEST_F(RTCStatsIntegrationTest, GetsStatsWhileClosingPeerConnection) {
+  StartCall();
+
+  rtc::scoped_refptr<RTCStatsObtainer> stats_obtainer =
+      RTCStatsObtainer::Create();
+  caller_->pc()->GetStats(stats_obtainer);
+  caller_->pc()->Close();
+
+  ASSERT_TRUE(stats_obtainer->report());
   EXPECT_EQ(stats_obtainer->report()->ToJson(),
             RTCStatsReportTraceListener::last_trace());
 }