Tomáš Hovorka
Tomáš Hovorka

Reputation: 29

How to process only last Task and discard previous in c#

I have a WPF application. Window includes datagrid for showing data and button for searching them. In viewmodel there is a method for loading data to the datagrid.

    public List<MyObject> DataGridData { get; set; }

    public void LoadDataToDatagrid(object obj)
    {
        Task.Run(() =>
        {
            DataGridData = new List<MyObject>(repository.GetData());
        });
    }

Everytime, when i click the button to load the data, the data is loaded to datagrid, but it takes a long time. So when i click the button more than once, the first data are loaded. I will start working with them and then new data are loaded again.

How can I stop previous tasks and load data only for last click button?

Thanks for your answers

Upvotes: 2

Views: 405

Answers (2)

Tom&#225;š Hovorka
Tom&#225;š Hovorka

Reputation: 29

Solved:

List<CancellationTokenSource> tokens = new List<CancellationTokenSource>();

public List<MyObject> DataGridData { get; set; }

public void LoadDataToDatagrid(object obj)
{
        foreach (var token in tokens)
            token.Cancel();

        CancellationTokenSource tokenSource = new CancellationTokenSource();
        tokens.Add(tokenSource);

        var task = Task.Run(() =>
        {
            return repository.GetData();
        }, tokenSource.Token);

        try
        {
            DataGridData = await task;
        }
        finally
        {
            tokenSource.Dispose();
            tokens.Remove(tokenSource);
        }
}

That code show only data from last method call withou freeze application. Thanks for answer Dmitry Bychenko.

Upvotes: 0

JonaFane
JonaFane

Reputation: 108

You could maybe disable the button until the content is loaded?

You would have to set your button disabled property to have a dependency on a bool in your ViewModel and then set it to true when you are adding to the datagrid and then set it to false when you are done. To do this, I am assuming you can raise events of some kind of:

NotifyPropertyChanged();

In XAML you would do something like this:

<Button IsEnabled="{Binding CanClose}"/>

Where CanClose is a bool in your ViewModel. When you change the state of the bool, you have to raise some kind of event. You can also disable the button first, then start filling the datagrid and when finished, enable it again?

Upvotes: 3

Related Questions