Why leaps exception in the load method? If it is to make simultaneous , everything works well . Tell me, please , what is the problem and how to fix it ?
public class MainViewModel : ViewModelBase
{
private readonly List<string> _listImageUri;
private int _currentIndex;
private ImageSource _currentImage;
public ObservableCollection<Image> CustomControls { get; set; } = new ObservableCollection<Image>();
public MainViewModel()
{
_listImageUri = new List<string>();
Load("путь к папке");
}
private async void Load(string s)
{
await Task.Run(() =>
{
foreach (var fileInfo in new DirectoryInfo(s).GetFiles())
{
_listImageUri.Add(fileInfo.FullName);
Image img = new Image(); // exception
img.Height = 100;
img.Margin = new Thickness(5);
img.Width = 100;
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(fileInfo.FullName);
bmp.DecodePixelWidth = 100;
bmp.EndInit();
img.Source = bmp;
CustomControls.Add(img);
OnPropertyChanged(nameof(CustomControls));
}
});
}
}
Exception
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: The calling thread must be STA, because many UI components require this.