应用场景
在winfrom 下通过表格实现数据的实时刷新,确保性能稳定界面流畅,本案例是通过AntdUI控件下的table控件实现的,实现逻辑不受限空间控件:
实现逻辑
1、想要数据自动刷新更新界面,需要使用实体类实现NotifyPropertyChangedBase进行通知控件更新
//自定义的通知类,以下可以简写
public class NotifyPropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private SynchronizationContext? _syncContext;
public void SetSynchronizationContext(SynchronizationContext context)
{
_syncContext = context;
}
protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
try
{
if (_syncContext != null && _syncContext != SynchronizationContext.Current)
{
_syncContext.Post(_ =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)),
null);
}
else
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
catch (Exception ex)
{
}
}
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
try
{
if (EqualityComparer<T>.Default.Equals(storage, value))
{
return false;
}
storage = value;
OnPropertyChanged(propertyName);
return true;
}
catch (Exception ex)
{
return false;
}
}
protected string fromateTime(string hr, string min, string sec)
{
return $"{hr}:{min}:{sec}";
}
}
//更新Model类
public class DemoModel : NotifyPropertyChangedBase
{
private string _name = string.Empty;
/// <summary>
/// 姓名
/// </summary>
public string Name
{
get => _name ;
set
{
if (_name == value) return;
_name = value;
OnPropertyChanged();
}
}
private int _age = 0;
/// <summary>
/// 年龄
/// </summary>
public string Age
{
get => _age;
set
{
if (_age== value) return;
_age= value;
OnPropertyChanged();
}
}
}
2、数据绑定控件更新
必须通过BingdList<T>承载数据集合,table控件通过table.Binding(dataList)进行绑定;
3、定时刷新列表数据
//定时刷新方法
public static void RefreshData()
{
// 临时禁用列表变更通知
if (dataList is BindingList<DemoModel> bindingList)
{
//暂停界面刷新
var oldRaise = bindingList.RaiseListChangedEvents;
bindingList.RaiseListChangedEvents = false;
try
{
Stopwatch stopwatch = Stopwatch.StartNew();
Parallel.ForEach(dataList, item =>
{
item.Age= new Random().Next(150);
item.Name= new Random().Next(1000).ToString();
});
stopwatch.Stop();
Logger.Info($"数据刷新完成,耗时:{stopwatch.ElapsedMilliseconds}毫秒");
}
catch (Exception)
{
bindingList.RaiseListChangedEvents = oldRaise;
bindingList.ResetBindings(); // 触发一次全局刷新
}
}
}
测试列表一次绑定5000条数据,每2秒对5000条数据进行刷新界面流畅无卡顿;

1万+

被折叠的 条评论
为什么被折叠?



