我的应用程序显示需要下载授权http头的图像。因此,我创建了一个自定义控件AuthenticatedImage
,该控件创建了具有必要标题的HttpClient,下载图像流并设置控制模板的控制源Image
。自定义控件从下载流设置图像源
打电话时bitmapImage.SetSource(stream)
我做错了什么与线程似乎因为我得到这个异常:
A first chance exception of type 'System.NotSupportedException' occurred in System.Windows.ni.dll
Additional information: Read is not supported on the main thread when buffering is disabled.
这是我的自定义控件的简化相关方法:
public override async void OnApplyTemplate()
{
base.OnApplyTemplate();
this.image = GetTemplateChild(imagePartName) as Image;
await this.SetSource(this.Source);
}
private async Task SetSource(Uri uri)
{
var stream = await DownloadImage(uri);
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
this.image.Source = bitmapImage;
}
private Task<Stream> DownloadImage(Uri uri)
{
var httpClientHandler = new HttpClientHandler();
var httpClient = new HttpClient(httpClientHandler);
httpClient.DefaultRequestHeaders.Add(/* custom header */);
return httpClient.GetStreamAsync(uri);
}
我寻找这样做的正确方法。
您是否使用post方法? – Jaihind
不,我正在下载一个图像,并使用GetStreamAsync,如你所见。 – siger