Отдельный поток под BitmapImage - C#
Формулировка задачи:
Есть метод:
Эта часть выдает ошибку:
До этого вызывал в нем, но отдельный метод Скорее всего придется загонять src картинок в "стринги" а затем новым потоком в BitmapImage. После завершения текущего.
private Task<IEnumerable<PageModel>> LoadContent(string uri)
{
return Enumerable.Range(0, 1)
.Select(url =>
{
return GetHttp(uri);
})
.Select(async content =>
{
var parser = new HtmlParser();
var document = parser.Parse(await content.ConfigureAwait(false));
return
document.QuerySelectorAll("div[role='main']")
.Select(element =>
element.InnerHtml.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
.TakeWhile(a => !a.Contains("<!--"))
.Select(con =>
{
var document2 = parser.Parse(con);
var result =
document2.All.Select
(n =>
{
var html = n.InnerHtml;
return
html.Contains("img") && html.Contains("src")
? new PageModel
{
Img = new BitmapImage(new Uri(document2.QuerySelector("img")
.GetAttribute("src"))),
}
: new PageModel
{
Content = document2.All
.Select(nod => nod.TextContent)
.First().Trim()
};
})
.First();
return result;
}).Where(html => !string.IsNullOrWhiteSpace(html.Content)
|| html.Img != null)
).First();
}).First();
}new PageModel
{
Img = new BitmapImage(new Uri(document2.QuerySelector("img")
.GetAttribute("src"))),
}
System.AggregateException: One or more errors occurred. (Приложение обратилось к интерфейсу, относящемуся к другому потоку. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))) ---> System.Exception: Приложение обратилось к интерфейсу, относящемуся к другому потоку. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
at Windows.UI.Xaml.Media.Imaging.BitmapImage..ctor(Uri uriSource)
at NashNovoaltaisk01.MainPage.<>c__DisplayClass10_2.<LoadContent>b__5(IElement n)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at NashNovoaltaisk01.MainPage.<>c__DisplayClass10_1.<LoadContent>b__4(String con)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
at System.Collections.ObjectModel.ObservableCollection`1.CopyFrom(IEnumerable`1 collection)
at NashNovoaltaisk01.MainPage.<>c.<GetContentAsync>b__7_1(IEnumerable`1 x)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Collections.ObjectModel.ObservableCollection`1.CopyFrom(IEnumerable`1 collection)
at NashNovoaltaisk01.MainPage.<GetContentAsync>d__7.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at NashNovoaltaisk01.MainPage.OnNavigatedTo(NavigationEventArgs e)
---> (Inner Exception #0) System.Exception: Приложение обратилось к интерфейсу, относящемуся к другому потоку. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
at Windows.UI.Xaml.Media.Imaging.BitmapImage..ctor(Uri uriSource)
at NashNovoaltaisk01.MainPage.<>c__DisplayClass10_2.<LoadContent>b__5(IElement n)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at NashNovoaltaisk01.MainPage.<>c__DisplayClass10_1.<LoadContent>b__4(String con)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
at System.Collections.ObjectModel.ObservableCollection`1.CopyFrom(IEnumerable`1 collection)
at NashNovoaltaisk01.MainPage.<>c.<GetContentAsync>b__7_1(IEnumerable`1 x)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Collections.ObjectModel.ObservableCollection`1.CopyFrom(IEnumerable`1 collection)
at NashNovoaltaisk01.MainPage.<GetContentAsync>d__7.MoveNext()<---
Закоментил участок, проблема не исчезла
System.AggregateException: One or more errors occurred. (Приложение обратилось к интерфейсу, относящемуся к другому потоку. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))) ---> System.Exception: Приложение обратилось к интерфейсу, относящемуся к другому потоку. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
at Windows.UI.Xaml.Controls.ItemsControl.put_ItemsSource(Object value)
at NashNovoaltaisk01.MainPage.<GetContentAsync>d__7.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at NashNovoaltaisk01.MainPage.OnNavigatedTo(NavigationEventArgs e)
---> (Inner Exception #0) System.Exception: Приложение обратилось к интерфейсу, относящемуся к другому потоку. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
at Windows.UI.Xaml.Controls.ItemsControl.put_ItemsSource(Object value)
at NashNovoaltaisk01.MainPage.<GetContentAsync>d__7.MoveNext()<---
Решил часть проблем - перекинув код вызова методов в
protected override async void OnNavigatedTo(NavigationEventArgs e)
private async Task GetContentAsync()
. Проблема сnew PageModel
{
Img = new BitmapImage(new Uri(document2.QuerySelector("img")
.GetAttribute("src"))),
}Решение задачи: «Отдельный поток под BitmapImage»
textual
Листинг программы
public class MainNewsData : INotifyPropertyChanged
{
private string imgSrcOld;
private string imgSrcNew;
public string ImgSrc
{
private get { return imgSrcNew; }
set
{
imgSrcNew = value;
Notify("ImgSrc");
}
}
public string Content { get; set; }
public string PageUri { get; set; }
private BitmapImage image;
public BitmapImage Image
{
get { return image; }
private set
{
if (imgSrcNew!=imgSrcOld || imgSrcNew==null)
{
image = new BitmapImage(new System.Uri(ImgSrc));
imgSrcOld = imgSrcNew;
Notify("Image");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void Notify(string notify) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(notify));
}