Skip to content

Commit

Permalink
use HttpClient to replace WebClient
Browse files Browse the repository at this point in the history
  • Loading branch information
kasperk81 committed Jun 19, 2024
1 parent 5e1b5b5 commit eed59a4
Showing 1 changed file with 18 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
using System.Net;
using System.Runtime.InteropServices;
using System.Windows.Forms.Layout;
using System.Windows.Forms.Primitives;

namespace System.Windows.Forms;

Expand All @@ -26,6 +25,9 @@ public partial class PictureBox : Control, ISupportInitialize
!AppContext.TryGetSwitch("System.Windows.Forms.PictureBox.UseWebRequest", out bool useWebRequest)
|| useWebRequest;

private static readonly HttpClient s_httpClient = !LocalAppContextSwitches.ServicePointManagerCheckCrl ? new() :
new(new HttpClientHandler { CheckCertificateRevocationList = true });

/// <summary>
/// The type of border this control will have.
/// </summary>
Expand Down Expand Up @@ -464,23 +466,26 @@ public void Load()
try
{
DisposeImageStream();
if (UseWebRequest())
Uri uri = CalculateUri(_imageLocation);
if (uri.IsFile)
{
LoadImageViaWebClient();
_localImageStreamReader = new StreamReader(uri.LocalPath);
Image img = Image.FromStream(_localImageStreamReader.BaseStream);
InstallNewImage(img, ImageInstallationType.FromUrl);
}
else
else if (UseWebRequest())
{
Uri uri = CalculateUri(_imageLocation);
if (uri.IsFile)
// Run async operation synchronously to avoid blocking UI thread and potential deadlocks.
Task.Run(async () =>
{
_localImageStreamReader = new StreamReader(uri.LocalPath);
Image img = Image.FromStream(_localImageStreamReader.BaseStream);
_uriImageStream = await s_httpClient.GetStreamAsync(uri).ConfigureAwait(false);
Image img = Image.FromStream(_uriImageStream);
InstallNewImage(img, ImageInstallationType.FromUrl);
}
else
{
throw new NotSupportedException(SR.PictureBoxRemoteLocationNotSupported);
}
}).GetAwaiter().GetResult();
}
else
{
throw new NotSupportedException(SR.PictureBoxRemoteLocationNotSupported);
}
}
catch
Expand Down

0 comments on commit eed59a4

Please sign in to comment.