77using System . Net ;
88using System . Runtime . InteropServices ;
99using System . Windows . Forms . Layout ;
10- using System . Windows . Forms . Primitives ;
1110
1211namespace System . Windows . Forms ;
1312
@@ -26,6 +25,9 @@ public partial class PictureBox : Control, ISupportInitialize
2625 ! AppContext . TryGetSwitch ( "System.Windows.Forms.PictureBox.UseWebRequest" , out bool useWebRequest )
2726 || useWebRequest ;
2827
28+ private static readonly HttpClient s_httpClient = ! LocalAppContextSwitches . ServicePointManagerCheckCrl ? new ( ) :
29+ new ( new HttpClientHandler { CheckCertificateRevocationList = true } ) ;
30+
2931 /// <summary>
3032 /// The type of border this control will have.
3133 /// </summary>
@@ -464,23 +466,26 @@ public void Load()
464466 try
465467 {
466468 DisposeImageStream ( ) ;
467- if ( UseWebRequest ( ) )
469+ Uri uri = CalculateUri ( _imageLocation ) ;
470+ if ( uri . IsFile )
468471 {
469- LoadImageViaWebClient ( ) ;
472+ _localImageStreamReader = new StreamReader ( uri . LocalPath ) ;
473+ Image img = Image . FromStream ( _localImageStreamReader . BaseStream ) ;
474+ InstallNewImage ( img , ImageInstallationType . FromUrl ) ;
470475 }
471- else
476+ else if ( UseWebRequest ( ) )
472477 {
473- Uri uri = CalculateUri ( _imageLocation ) ;
474- if ( uri . IsFile )
478+ // Run async operation synchronously to avoid blocking UI thread and potential deadlocks.
479+ Task . Run ( async ( ) =>
475480 {
476- _localImageStreamReader = new StreamReader ( uri . LocalPath ) ;
477- Image img = Image . FromStream ( _localImageStreamReader . BaseStream ) ;
481+ _uriImageStream = await s_httpClient . GetStreamAsync ( uri ) . ConfigureAwait ( false ) ;
482+ Image img = Image . FromStream ( _uriImageStream ) ;
478483 InstallNewImage ( img , ImageInstallationType . FromUrl ) ;
479- }
480- else
481- {
482- throw new NotSupportedException ( SR . PictureBoxRemoteLocationNotSupported ) ;
483- }
484+ } ) . GetAwaiter ( ) . GetResult ( ) ;
485+ }
486+ else
487+ {
488+ throw new NotSupportedException ( SR . PictureBoxRemoteLocationNotSupported ) ;
484489 }
485490 }
486491 catch
0 commit comments