Привязка элемента ListBox происходит медленно и зависает пользовательский интерфейс WPF C#C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Привязка элемента ListBox происходит медленно и зависает пользовательский интерфейс WPF C#

Сообщение Anonymous »

Movie.cs

Код: Выделить всё

public class Movie : INotifyPropertyChanged
{

public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}

private string name;
public string Name { get; set; }

private int id;
public int Id { get; set; }

private string ratingNumber;
public string RatingNumber { get; set; }

private BitmapSource _bitmap;
public BitmapSource Bitmap
{
get; set;
}

private double rating;
public double Rating
{
get
{
return rating;
}
set
{
rating = value;
rating = rating / 2;
}
}

private ShowType showType;
public ShowType ShowType { get; set; }

}
Service.cs

Код: Выделить всё

 public static FastObservableCollection PopularMovies = new FastObservableCollection();
public static async Task GetPopularMoviesAsync(string language, int page)
{
PopularMovies.Clear();
var popularMovies = await client.GetMoviePopularListAsync(language, page);
foreach (var movie in popularMovies.Results)
{
Movie mov = new Movie()
{
Bitmap = await GetImage(client.GetImageUrl("w500", movie.PosterPath).AbsoluteUri,ImageType.Poster),
Id = movie.Id,
Name = movie.Title,
Rating = movie.VoteAverage,
RatingNumber = movie.VoteAverage.ToString(),
ShowType = ShowType.Movie,
};
if (PopularMovies.Any(x => x.Id == movie.Id))
{

}
else
{
PopularMovies.Add(mov);
}
}
}
Home.xaml.cs

Код: Выделить всё

private async void OnLoad()
{
var tasks = new List();
if (Service.PopularMovies.Count == 0)
{
tasks.Add(Service.GetPopularMoviesAsync("en",1));
}
await Task.WhenAll
}

Код: Выделить всё

  public static async Task GetImage(string url,ImageType imageType)
{
var bitmapImage = new BitmapImage(new Uri(url,UriKind.Absolute));
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
return bitmapImage;
}

Код: Выделить всё

public class FastObservableCollection  : ObservableCollection
{
private readonly object locker = new object();

/// 
/// This private variable holds the flag to
/// turn on and off the collection changed notification.
/// 
private bool suspendCollectionChangeNotification;

/// 
/// Initializes a new instance of the FastObservableCollection class.
/// 
public FastObservableCollection()
: base()
{
this.suspendCollectionChangeNotification = false;
}

/// 
/// This event is overriden CollectionChanged event of the observable collection.
/// 
public override event NotifyCollectionChangedEventHandler CollectionChanged;

/// 
/// This method adds the given generic list of items
/// as a range into current collection by casting them as type T.
/// It then notifies once after all items are added.
/// 
/// 
The source collection.
public void AddItems(IList items)
{
lock (locker)
{
this.SuspendCollectionChangeNotification();
foreach (var i in items)
{
InsertItem(Count, i);
}
this.NotifyChanges();
}
}

/// 
/// Raises collection change event.
/// 
public void NotifyChanges()
{
this.ResumeCollectionChangeNotification();
var arg
= new NotifyCollectionChangedEventArgs
(NotifyCollectionChangedAction.Reset);
this.OnCollectionChanged(arg);
}

/// 
/// This method removes the given generic list of items as a range
/// into current collection by casting them as type T.
/// It then notifies once after all items are removed.
/// 
/// The source collection.
public void RemoveItems(IList items)
{
lock (locker)
{
this.SuspendCollectionChangeNotification();
foreach (var i in items)
{
Remove(i);
}
this.NotifyChanges();
}
}

/// 
/// Resumes collection changed notification.
/// 
public void ResumeCollectionChangeNotification()
{
this.suspendCollectionChangeNotification = false;
}

/// 
/// Suspends collection changed notification.
/// 
public void SuspendCollectionChangeNotification()
{
this.suspendCollectionChangeNotification = true;
}

/// 
/// This collection changed event performs thread safe event raising.
/// 
/// The event argument.
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
// Recommended is to avoid reentry
// in collection changed event while collection
// is getting changed on other thread.
using (BlockReentrancy())
{
if (!this.suspendCollectionChangeNotification)
{
NotifyCollectionChangedEventHandler eventHandler =
this.CollectionChanged;
if (eventHandler == null)
{
return;
}

// Walk thru invocation list.
Delegate[] delegates = eventHandler.GetInvocationList();

foreach
(NotifyCollectionChangedEventHandler handler in delegates)
{
// If the subscriber is a DispatcherObject and different thread.
DispatcherObject dispatcherObject
= handler.Target as DispatcherObject;

if (dispatcherObject != null
&& !dispatcherObject.CheckAccess())
{
// Invoke handler in the target dispatcher's thread...
// asynchronously for better responsiveness.
dispatcherObject.Dispatcher.BeginInvoke
(DispatcherPriority.DataBind, handler, this, e);
}
else
{
// Execute handler as is.
handler(this, e);
}
}
}
}
}
}
Это медленно, зависает пользовательский интерфейс и задерживает отображение изображений до завершения загрузки всего списка. Как я могу это исправить? Мой старый проект 2018 года с теми же кодами, что и выше, работает отлично, он быстрый и не блокирует пользовательский интерфейс. Но для .net 8.0 это не так. Я не понимаю, что изменила Microsoft.


Подробнее здесь: https://stackoverflow.com/questions/791 ... pf-c-sharp
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»