Results subscribe to parameters

Problem: User needs to see the result of changes to a non-destructive job or query's parameters immediately following the change

Pattern: Code that generates the results runs on a separate thread and is interrupted and restarted by a control module that subscribes to PropertyChanged events coming from a structure bound to the UI's controls

Example:

class JobCriteria : INotifyPropertyChanged
{
    public bool MinimumAge
    {
        get { return _minimumAge; }
        set {
            _minimumAge = value;
            PropertyChanged(this, new PropertyChangedEventArgs("MinimumAge"));
        }
    }

    // ... other properties ...
}

// In code for the UI controller...

void JobCriteria_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    JobCriteria critera = sender as JobCriteria;

    if (ResultsWorker != null && ResultsWorker.IsBusy)
        ResultsWorker.CancelAsync();

    // ... clear the UI of old results ...

    ResultsWorker = new BackgroundWorker();
    // ... setup BackgroundWorker ...
    ResultsWorker.RunWorkerAsync(criteria);
}

void ResultsWorker_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker myWorker = sender as BackgroundWorker;
    JobCriteria criteria = e.Argument as JobCriteria;
    while (!myWorker.CancellationPending)
    {
        // ... compute results ...
        foreach (InterestingDataType result in theResults)
            myWorker.ReportProgress(0, result);
    }
}

void ResultsWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    InterestingDataType result = e.UserState as InterestingDataType;
    // ... update the UI with the new result
}

Discussion: The user will be able to change the criteria for the job--be it a search or some other non-destructive operation--and see the display of results clear and begin rebuilding instantaneously. In code, the JobCriteria_PropertyChanged event handler is subscribed to the PropertyChanged event of an instance of JobCriteria, which is the same instance bound to the controls in the UI. Upon handling a PropertyChanged event it halts any current background thread that may already be running, clears the UI of any old results, and then starts a new BackgroundWorker thread to act upon the new critera.

 New results are marshaled back into the UI's thread by raising the ReportProgress event.
Comments