Skip to content

Instantly share code, notes, and snippets.

@antonfirsov
Last active February 21, 2025 18:00
Show Gist options
  • Save antonfirsov/f0336d6b50e01fb822a3af218f5db4fc to your computer and use it in GitHub Desktop.
Save antonfirsov/f0336d6b50e01fb822a3af218f5db4fc to your computer and use it in GitHub Desktop.
HttpHandlerDiagnosticListener duplicate event repro
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
class Program
{
private const string RemoteEchoServer =
"http://corefx-net-http11.azurewebsites.net/Echo.ashx";
// "http://example.com"; // Other hosts work well
static async Task Main()
{
var eventRecords = new EventObserverAndRecorder();
// ActivityIdFormat.Hierarchical works well
Activity.DefaultIdFormat = ActivityIdFormat.W3C;
// HttpWebRequest works well
using (var client = new HttpClient())
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, RemoteEchoServer))
{
(await client.SendAsync(request, default)).Dispose();
}
// PRINTS:
// System.Net.Http.Desktop.HttpRequestOut.Start: HttpWebRequest[6044116] -- http://corefx-net-http11.azurewebsites.net/Echo.ashx
// System.Net.Http.Desktop.HttpRequestOut.Start: HttpWebRequest[6044116] -- http://corefx-net-http11.azurewebsites.net/Echo.ashx
// System.Net.Http.Desktop.HttpRequestOut.Stop: HttpWebRequest[6044116] -- http://corefx-net-http11.azurewebsites.net/Echo.ashx
}
}
internal class CallbackObserver<T> : IObserver<T>
{
public CallbackObserver(Action<T> callback) { _callback = callback; }
public void OnCompleted() { }
public void OnError(Exception error) { }
public void OnNext(T value) { _callback(value); }
private Action<T> _callback;
}
internal class EventObserverAndRecorder : IObserver<KeyValuePair<string, object>>
{
public EventObserverAndRecorder()
{
DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(diagnosticListener =>
{
if (diagnosticListener.Name == "System.Net.Http.Desktop")
{
diagnosticListener.Subscribe(this);
}
}));
}
public void OnCompleted() { }
public void OnError(Exception error) { }
public void OnNext(KeyValuePair<string, object> record)
{
HttpWebRequest r = (HttpWebRequest)record.Value.GetType().GetProperty("Request").GetValue(record.Value);
Console.WriteLine($"{record.Key}: HttpWebRequest[{RuntimeHelpers.GetHashCode(r)}] -- {r.RequestUri}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment