lvermeulen / Bitbucket.Net

C# client for Atlassian Bitbucket Server
MIT License
32 stars 18 forks source link

support CancellationToken in requests #27

Open drewburlingame opened 2 years ago

drewburlingame commented 2 years ago

I have a console app using this library. Querying the list of repositories for one server takes 90 seconds. I can't cancel the command because I can't pass the CancellationToken through the methods. I looked at forking this but there were too many methods for me to update. I ended up with the following workaround. It works but took my a while to determine how to do. Maybe it would even be helpful just to link to an example like this until such time CancellationToken is supported?


        MyHttpClientHandler.CancellationToken = context.CancellationToken;
        FlurlHttp.GlobalSettings.HttpClientFactory = new MyDefaultHttpClientFactory();

        public class MyDefaultHttpClientFactory : DefaultHttpClientFactory
        {
            public override HttpMessageHandler CreateMessageHandler() => (HttpMessageHandler)new MyHttpClientHandler()
            {
                AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate)
            };
        }

        public class MyHttpClientHandler : HttpClientHandler
        {
            internal static CancellationToken CancellationToken;

            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                // ignore the default token
                return base.SendAsync(request, CancellationToken);
            }

            protected override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                // ignore the default token
                return base.Send(request, CancellationToken);
            }
        }