Skip to content

Commit

Permalink
fix: PictureBox.LoadAsync throws PlatformNotSupportedException
Browse files Browse the repository at this point in the history
Async delegates have been deprecated in .NET Core (see https://github.com/dotnet/corefx/issues/5940)
for reasons such as:
* Async delegates use deprecated IAsyncResult-based async pattern.
This pattern is generally not supported throughout .NET Core base libraries.
* Async delegates depend on remoting (System.Runtime.Remoting) under the
hood. Remoting is not supported in .NET Core.

For more detailed reasons and migration strategies please refer to
https://devblogs.microsoft.com/dotnet/migrating-delegate-begininvoke-calls-for-net-core/

In case of WinForms, async pattern predates the Task-based Asynchronous
Pattern and it does not return awaitables.
In order to minimise the change to the public API surface we continue
to expose the existing API and just re-route the image loading routine
to a `Task` runner under the covers.

Fixes dotnet#242
Fixes dotnet#1548
  • Loading branch information
RussKie committed Aug 30, 2019
1 parent ddf07ce commit e8bb804
Show file tree
Hide file tree
Showing 21 changed files with 472 additions and 16 deletions.
20 changes: 7 additions & 13 deletions src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System.Net;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms.Layout;

namespace System.Windows.Forms
Expand Down Expand Up @@ -48,6 +49,7 @@ public class PictureBox : Control, ISupportInitialize

// Instance members for asynchronous behavior
private AsyncOperation _currentAsyncLoadOperation;

private string _imageLocation;
private Image _initialImage;
private Image errorImage;
Expand Down Expand Up @@ -555,19 +557,11 @@ public void LoadAsync()

WebRequest req = WebRequest.Create(CalculateUri(_imageLocation));

// Invoke BeginGetResponse on a threadpool thread, as it has
// unpredictable latency, since, on first call, it may load in the
// configuration system (this is NCL
(new WaitCallback(BeginGetResponseDelegate)).BeginInvoke(req, null, null);
}

/// <summary>
/// Solely for calling BeginGetResponse itself asynchronously.
/// </summary>
private void BeginGetResponseDelegate(object arg)
{
WebRequest req = (WebRequest)arg;
req.BeginGetResponse(new AsyncCallback(GetResponseCallback), req);
Task.Run(() =>
{
// Invoke BeginGetResponse on a threadpool thread, as it has unpredictable latency
req.BeginGetResponse(new AsyncCallback(GetResponseCallback), req);
});
}

private void PostCompleted(Exception error, bool cancelled)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,14 @@
<Link>Panels.Designer.cs</Link>
<DependentUpon>Panels.cs</DependentUpon>
</Compile>
<Compile Include="..\WinformsControlsTest\PictureBoxes.cs">
<Link>PictureBoxes.cs</Link>
<SubType>Form</SubType>
</Compile>
<Compile Include="..\WinformsControlsTest\PictureBoxes.Designer.cs">
<Link>PictureBoxes.Designer.cs</Link>
<DependentUpon>PictureBoxes.cs</DependentUpon>
</Compile>
<Compile Include="..\WinformsControlsTest\PropertyGrid.cs">
<Link>PropertyGrid.cs</Link>
<SubType>Form</SubType>
Expand Down Expand Up @@ -304,6 +312,10 @@
<Link>Panels.resx</Link>
<DependentUpon>Panels.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="..\WinformsControlsTest\PictureBoxes.resx">
<Link>PictureBoxes.resx</Link>
<DependentUpon>PictureBoxes.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="..\WinformsControlsTest\PropertyGrid.resx">
<Link>PropertyGrid.resx</Link>
<DependentUpon>PropertyGrid.cs</DependentUpon>
Expand Down Expand Up @@ -364,6 +376,4 @@
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="Build" Condition="'$(OS)' != 'Windows_NT'">
</Target>
</Project>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -112,5 +112,10 @@ private void RichTextBoxes_Click(object sender, EventArgs e)
{
new RichTextBoxes().Show();
}

private void PictureBoxes_Click(object sender, EventArgs e)
{
new PictureBoxes().Show();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
Expand Down Expand Up @@ -58,4 +117,4 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
</root>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinformsControlsTest
{
public partial class PictureBoxes : Form
{
private const string Heading = "PictureBox tests";
private bool _isLoading;

public PictureBoxes()
{
InitializeComponent();
Text = Heading;
}

private void btnloadImage_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(imageUri.Text))
{
pictureBox1.Image = null;
if (_isLoading)
{
pictureBox1.CancelAsync();
}

return;
}

try
{
_isLoading = true;
pictureBox1.WaitOnLoad = false;
pictureBox1.LoadAsync(imageUri.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
_isLoading = false;
Text = Heading;

if (e.Cancelled)
{
MessageBox.Show("Image loading cancelled");
}

if (e.Error != null)
{
MessageBox.Show(e.Error.Message, $"{e.Error.GetType().FullName} occurred");
}
}

private void pictureBox1_LoadProgressChanged(object sender, ProgressChangedEventArgs e)
{
Text = $"{Heading}: loading image progress: {e.ProgressPercentage}%";
}
}
}
Loading

0 comments on commit e8bb804

Please sign in to comment.