我有这个奇怪的问题。
我在主线程上的代码:
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler((ss, ee) =>
{
Dispatcher.BeginInvoke(() =>
{
try
{
BitmapImage bi = new BitmapImage();
bi.SetSource(ee.Result);
WriteableBitmap wb = new WriteableBitmap(bi);
_okAction.Invoke(linkTexBox.Text, wb);
theProgressBarDialog.Close();
}
catch (Exception)
{
theProgressBarDialog.Close();
string msg = "Cannot fetch the image. Please make sure the image URL is correct";
MessageBox.Show(msg);
}
});
});
client.OpenReadAsync(new Uri("Image URL without cross domain problem"));
theProgressBarDialog.Show();
图像已成功加载,并在我的画布上呈现。
奇怪的行为有时是,我的整个 Silverlight 应用程序似乎冻结,该应用程序不响应任何用户操作,除了右键单击,它会弹出默认的 Silverlight 上下文菜单。
按钮被强制禁用。
调试时,不会抛出异常。
编辑:如果我设置client.AllowReadStreamBuffering = false
,我会得到异常:
{System.NotSupportedException: Read is not supported on the main thread when buffering is disabled.
at MS.Internal.InternalNetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Windows.Media.Imaging.BitmapSource.ReadStream(Stream streamSource, Byte[]& buffer, Int32& position)
at System.Windows.Media.Imaging.BitmapSource.SetSourceInternal(Stream streamSource)
at System.Windows.Media.Imaging.BitmapImage.SetSourceInternal(Stream streamSource)
at System.Windows.Media.Imaging.BitmapSource.SetSource(Stream streamSource)
at ToonGui.ImportImageDialog.<>c__DisplayClass2.<OKButton_Click>b__1()}
[System.NotSupportedException]: {System.NotSupportedException: Read is not supported on the main thread when buffering is disabled.
at MS.Internal.InternalNetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Windows.Media.Imaging.BitmapSource.ReadStream(Stream streamSource, Byte[]& buffer, Int32& position)
at System.Windows.Media.Imaging.BitmapSource.SetSourceInternal(Stream streamSource)
at System.Windows.Media.Imaging.BitmapImage.SetSourceInternal(Stream streamSource)
at System.Windows.Media.Imaging.BitmapSource.SetSource(Stream streamSource)
at ToonGui.ImportImageDialog.<>c__DisplayClass2.<OKButton_Click>b__1()}
Data: {System.Collections.ListDictionaryInternal}
InnerException: null
Message: "Read is not supported on the main thread when buffering is disabled."
StackTrace: " at MS.Internal.InternalNetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count)\r\n at System.Windows.Media.Imaging.BitmapSource.ReadStream(Stream streamSource, Byte[]& buffer, Int32& position)\r\n at System.Windows.Media.Imaging.BitmapSource.SetSourceInternal(Stream streamSource)\r\n at System.Windows.Media.Imaging.BitmapImage.SetSourceInternal(Stream streamSource)\r\n at System.Windows.Media.Imaging.BitmapSource.SetSource(Stream streamSource)\r\n at ToonGui.ImportImageDialog.<>c__DisplayClass2.<OKButton_Click>b__1()"
我是否必须使用一个BackgroundWorker
类来让下载任务在另一个线程中运行?