TheLastGIS
TheLastGIS

Reputation: 434

Property value different in Task

For some reason the IsFiltered property is set to true in the EnterPressed method. Once entering the Task, the property then comes back as false. Once leaving the Task however it returns back to true (then false in the Remove Progress method).

What am I missing? Can someone provide a link or tutorial that could point me in the right direction.

Using C#, Caliburn Micro and VS2017.

public bool IsFiltering
    {
        get;
        private set;
    }

    public bool ShowGrid
    {
        get
        {
            return !this.IsFiltering;
        }
    }

    public void SetProgress()
    {
        this.IsFiltering = true;

        NotifyOfPropertyChange("IsFiltering");
        NotifyOfPropertyChange("ShowGrid");
    }

public void EnterPressed()
    {
        SetProgress();

        Task.Run(() =>
        {
            if (this.searchFilter != "")
            {
                var filtered = Expenses.Where(exp => exp.ExpenseDescription.StartsWith(searchFilter.ToUpper())).ToList();
                var obsFiltered = new ObservableCollection<Models.Expense>(filtered);
                this.transactionReader.Expenses = obsFiltered;
                NotifyOfPropertyChange(() => Expenses);
            }

            Debug.WriteLine("EnterPressed called :: searchFilter is: " + this.searchFilter);
        });

        RemoveProgress();
    }

Upvotes: 0

Views: 148

Answers (2)

Antoine V
Antoine V

Reputation: 7204

You don't await your task. That means your Task.Run maybe executes after RemoveProgress. So, this is the flow of execution

SetProgress set true, then, it executes RemoveProgress, your property is still true.

RemoveProgress receives your property as true and sets it to false. Next, it runs the task, and your property is false inside it.

Try to organize your code, think about await or ContinueWith the task

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064324

Task.Run schedules work on the thread pool - i.e. at some undefined point in the future. What you have is basically:

  • mark it in progress
  • schedule some work to happen at some undefined point in the future
  • mark it not in progress

In almost all cases, the thread-pool won't have even dequeued that item by the time you mark it not in progress, let alone started running it.

Maybe mark it in-progress/not-in-progress as part of the scheduled work, i.e. inside the Task.Run() callback.

Upvotes: 2

Related Questions