Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

C# WPF DispatcherTimer freezes on mouse hover over Window

In the DataGrid element, I create a table with Items, which has columns: ID, Name and Timer. All this is tied to me through "Binding". Next, I run StopWatch on each item and a static DispatcherTimer to update the state in the UI. Everything works fine until I hover the mouse over the window - all the timers immediately start to freeze. This is most likely due to the fact that the mouse event and the DispatcherTimer are on the same thread. Tried using System.Timers.Timer - it also hangs and does not update information like DispatcherTimer

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        var i = Enumerable.Range(0, 20).Select(x => new Item("Item: " + x));
        Items = new ObservableCollection<Item>(i);
       
        DataContext = this;
    }

    public ObservableCollection<Item> Items { get; set; }
}

public class Item : INotifyPropertyChanged
{
    public string Id { get; set; }
    public string Name { get; set; }

    private TimeSpan _timerString;
    public TimeSpan TimerString
    {
        get => _timerString;
        set
        {
            _timerString = value;
            OnPropertyChanged();
        }
    }

    public Stopwatch sw = new Stopwatch();
    private static DispatcherTimer dt = new DispatcherTimer();

    public Item(string Name)
    {
        Id = Guid.NewGuid().ToString();
        this.Name = Name;
        //dt.Tick += (s, e) => { TimerString = sw.Elapsed; };
        dt.Tick += (s, e) => TimerString = sw.Elapsed;
        dt.Interval = TimeSpan.FromSeconds(1);
        if(!dt.IsEnabled)
        dt.Start();
        sw.Start();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged([CallerMemberName] string prop = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...